【问题标题】:How modify a class attribute through a reference of it in njit function?如何通过在 njit 函数中的引用来修改类属性?
【发布时间】:2018-03-27 09:10:44
【问题描述】:

我想更新 njit 函数中的类属性,但我事先不知道变量名称。为了说明这一点,我制作了以下代码

from numba import jitclass, jit, njit
from numba import int32, float64
import numpy as np

spec = [('A' ,float64),
        ('B' ,float64)]

@jitclass(spec, )
class myClass():
    def __init__(self):
        self.A = 1.
        self.B = 1.
    def add_A_and_B(self):
        return self.A + self.B

class essai():
    def __init__(self):
        self.C = myClass()

    def compute(self):
        mystring = 'C.A' # parameter that I want update
        nameclass, nameparam = mystring.split('.') # get the class name and the variable to update
        tp = np.linspace(0, 100, num = 101)
        val_A = np.linspace(0, 100, num = 101)
        ref = getattr(getattr(self,nameclass),nameparam) # Doesn't work, trying to get a reference to a class attribute C.A
        y= solve1(self.C,tp,ref,val_A) # pass the reference to the njit function to update C.A in the njit function
        print(y)


@njit(fastmath=True)
def solve1(C,tp,param,paramvalues):
    y = np.zeros(len(tp), )
    for idx, t in enumerate(tp):
        param=paramvalues[idx]
        #C.A=paramvalues[idx] # what I expect the previous line to do
        y[idx] = C.add_A_and_B()
    return y

E=essai()
E.compute()

我要更新的变量是mystring = 'C.A',但在我的完整代码中,这来自用户输入。所以我想要做的是获取该变量的引用,我尝试了ref = getattr(getattr(self,nameclass),nameparam),但这不起作用。一旦我有了这个引用,我就可以将它传递给solve1njit 函数,以便在njit 函数中更新C.A。 所以我运行我得到的代码

[ 2.  2.  2.  2.  2.  2.

而不是

[   1.    2.    3.    4.    5. .... 

如果我在solve1函数中使用C.A=paramvalues[idx]

所以问题是如何使用包含我要更新的变量名称的字符串(在我的情况下为 mystring = 'C.A')更新 njitfunction 中 C 的属性 A

【问题讨论】:

    标签: python class reference numba


    【解决方案1】:

    1) 引用,因为您希望能够通过直接分配给它来使用它 (param=...) 在 python 中不存在。分配给没有点或 [] 修饰符的左值总是重新绑定该名称,无论是否在 numba 中。编辑:澄清一下,如果名称标有global(全局变量)或nonlocal(封闭变量),则不正确,但此处均不适用。

    2) 在 nopython 模式下,numba 需要在编译时知道您分配给哪个属性(本质上是计算 c 结构的偏移量),所以我认为您能做的最好的事情就是编译两个版本的函数。

    【讨论】:

    • 何不...这不是我所期望的。但这是有道理的。谢谢你的详细信息
    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多