gpt4 book ai didi

python - Cython 无法使用 setattr

转载 作者:行者123 更新时间:2023-11-28 17:41:10 28 4
gpt4 key购买 nike

我在 cython 中有一个 cdef 类,我想用 setattr 内置函数初始化它的字段。但是,当我这样做时出现执行错误:

/path/.../cimul.cpython-34m.so in cimul.Simulation.__init__ (cimul.c:5100)()
AttributeError: 'Simulation' object has no attribute 'Re'

我的代码如下:

cdef class Simulation:
cdef double Re, Pr, Ra, a, dt_security
cdef int Nz, NFourier, freq_output, freq_critical_Ra, maxiter
cdef bool verbose

def __init__(self, *args, **kargs):
param_list = {'Re': 1, 'Pr': 1, 'Ra': 1, 'a' : 1, 'Nz': 100,
'NFourier': 50, 'dt_security': 0.9,
'maxiter': 100, 'freq_output': 10,
'freq_critical_Ra':50, 'verbose': False}
# save the default parameters
for param, value in param_list.items():
setattr(self, param, value)

你知道我该如何规避这个问题吗?

最佳答案

  • 当在一个类中定义(没有公共(public)的)属性时,您真正做的是在 C 结构中定义一些字段。因此在编译(Cython + C)之后,属性的名称丢失了,它们仅由 C 结构开头的一些偏移量标识。因此,无法从 Python 访问它们。

  • 如果您添加 cdef public,他们会在 Cython 中添加一些 property访问函数,它不仅允许从 Python 进行访问,而且还保留关联标识符 <--> 在 C 结构中的偏移量。通过这些属性函数会产生轻微的开销。另请注意,这些函数执行 Python -> C 类型检查/转换。

现在回答您的问题,您需要以某种方式保持关联标识 <--> 偏移。如果你想让事情快点,唯一的方法就是手工完成:

self.RE = param_list['RE']   # self.RE is a C struct access
self.Pr = param_list['Pr']
...

关于python - Cython 无法使用 setattr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com