【发布时间】: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