cython class 属性为 python 对象实例

cython class with an attributes as python object instance

让我们举个例子。

cdef class Example:
    attr2 = None
    cdef attr3
    cdef object attr4
    def __init__(self):
        self.attr1 = Obj()
        self.attr2 = Obj()
        self.attr3 = Obj()
        self.attr4 = Obj()

分配给 self.attr1 的行将引发 AttributeError 说:“object has no attribute 'attr1'.

如果尝试使用 self.attr2,它也会引发异常,但会显示消息:“对象属性 'attr2' 是只读的".

并且如果使用关键字cdef,并且它没有显式类型,编译过程将失败。

如果此属性定义为 object 类型,它看起来不错。但是 Example class 的不同实例将像单例一样具有此 attr4 并且与其中之一的任何交互对于其他实例,在这种情况下,我希望每个实例都有一个唯一的 Obj() 实例。

您可以尝试这样的操作:

class Obj(object):
    # At first I define a class Obj() to match your example
    def __init__(self):
        self.abc = 32
        self.xyz = "xyzxyz"

# Then I can define the Example class
cdef class Example:
    cdef public:
        object attr1, attr2, attr3, attr4
    def __init__(self):
        self.attr1 = Obj()
        self.attr2 = Obj()
        self.attr3 = Obj()
        self.attr4 = Obj()

似乎 cythonized/compiled 没有错误,您可以访问与 Obj 对象相关的属性:

In [11]:
a = Example()
a.attr1.abc
​
Out[11]:
32