是否可以通过 njit 函数中的名称更改 class 变量?
is it possible to change a class variable through its name in a njit function?
我试图通过名称修改 class 的变量,所以基本上我所做的就是调用 setattr
函数。
我的问题是当我尝试使用 numba
njit
装饰器时,它不再起作用了。
那么在 numba
中是否有解决方法来做同样的事情?
import numba as nb
class A():
def __init__(self):
self.a =0.
@nb.njit()
def test(A,s):
setattr(A,s,1)
A = A()
s = 'a'
print(A.a)
test(A,s)
print(A.a)
更新
是否可以在 test
函数中调用被 @nb.njit
装饰器排除的函数。在下面的示例中,无法编译 var_update(A,s,1)
函数?
import numba as nb
class A():
def __init__(self):
self.a =0.
def set_a(self,a):
self.a=a
@nb.njit()
def test(A,s):
var_update(A,s,1) # this function could not be compiled?
def var_update(Obj, s , val):
setattr(Obj,s,val)
CA = A()
s = 'a'
print(CA.a)
test(CA,s)
print(CA.a)
is it possible to change a class variable through its name in a njit function?
没有。目前(使用 numba 0.43.1)nopython 模式的 numba 函数是不可能的。它在您的示例中不起作用的原因有两个:
- 在 nopython 模式下,numba 仅支持非常有限的 类。不支持自定义 类(
numba.jitclass
除外)。
setattr
完全不受 numba 支持(参见 "Built-in functions" section in "Supported Python features" in the numba documentation)。
但是,如果您对如何设置自定义属性 类(但不是动态名称)感兴趣,您可以使用 jitclass
:
import numba as nb
@nb.jitclass([('a', nb.float64)])
class A():
def __init__(self):
self.a = 0.0
@nb.njit
def test(instance):
instance.a = 1
A = A()
print(A.a)
test(A)
print(A.a)
请注意,如果您想使用自定义 类 和 setattr
,那么我的建议是在 numba 函数的 之外 执行此操作。 Numba 非常适合数字运算和数组处理,但它不是通用工具!如果你想要一个更通用的工具,那么 Cython 可能会更好。
根据我的经验:如果它与循环无关并且不涉及数字或数组,那么不要指望 numba 会更有效率 - 这当然过于简单化但在过去为我提供了很好的指导(参见例如我在 ) 上的回答。
我试图通过名称修改 class 的变量,所以基本上我所做的就是调用 setattr
函数。
我的问题是当我尝试使用 numba
njit
装饰器时,它不再起作用了。
那么在 numba
中是否有解决方法来做同样的事情?
import numba as nb
class A():
def __init__(self):
self.a =0.
@nb.njit()
def test(A,s):
setattr(A,s,1)
A = A()
s = 'a'
print(A.a)
test(A,s)
print(A.a)
更新
是否可以在 test
函数中调用被 @nb.njit
装饰器排除的函数。在下面的示例中,无法编译 var_update(A,s,1)
函数?
import numba as nb
class A():
def __init__(self):
self.a =0.
def set_a(self,a):
self.a=a
@nb.njit()
def test(A,s):
var_update(A,s,1) # this function could not be compiled?
def var_update(Obj, s , val):
setattr(Obj,s,val)
CA = A()
s = 'a'
print(CA.a)
test(CA,s)
print(CA.a)
is it possible to change a class variable through its name in a njit function?
没有。目前(使用 numba 0.43.1)nopython 模式的 numba 函数是不可能的。它在您的示例中不起作用的原因有两个:
- 在 nopython 模式下,numba 仅支持非常有限的 类。不支持自定义 类(
numba.jitclass
除外)。 setattr
完全不受 numba 支持(参见 "Built-in functions" section in "Supported Python features" in the numba documentation)。
但是,如果您对如何设置自定义属性 类(但不是动态名称)感兴趣,您可以使用 jitclass
:
import numba as nb
@nb.jitclass([('a', nb.float64)])
class A():
def __init__(self):
self.a = 0.0
@nb.njit
def test(instance):
instance.a = 1
A = A()
print(A.a)
test(A)
print(A.a)
请注意,如果您想使用自定义 类 和 setattr
,那么我的建议是在 numba 函数的 之外 执行此操作。 Numba 非常适合数字运算和数组处理,但它不是通用工具!如果你想要一个更通用的工具,那么 Cython 可能会更好。
根据我的经验:如果它与循环无关并且不涉及数字或数组,那么不要指望 numba 会更有效率 - 这当然过于简单化但在过去为我提供了很好的指导(参见例如我在