如何向 cython 类添加一个静态的类型化成员?添加类型化实例成员的语法使用如下语法(例如):
import cython
cdef class NoStaticMembers:
cdef public int instanceValue # but, how do I create a static member??
def __init__(self, int value):
self.instanceValue = value
最佳答案
仅仅因为您可以在 C 中完成并不意味着您可以在 Cython 中完成。
解决方法可能涉及使用全局变量和类属性,以便您可以通过类实例访问它们。我不确定它是否真的比使用全局变量更好
import cython
cdef int MyClass_static_variable
cdef class MyClass:
property static_variable:
def __get__(self):
return MyClass_static_variable
def __set__(self, x):
global MyClass_static_variable
MyClass_static_variable = x
您必须测量通过该方法损失了多少速度(如果可以的话,也许可以考虑制作 __get__
和 __set__
cpdef
- 我不确定)。唯一不允许您像真正的静态变量那样做的事情是将其作为 MyClass.static_variable
进行访问。
关于python - 如何将静态成员添加到 Cython 类(来自 python,而不是 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29025923/