我有Cython类:
cdef class Blah:
cdef __cinit__(self, arg): ...
然后我想将其继承为python类:
class Foo(Blah):
def __init__(self,arg):
super().__cinit__(arg)
我该怎么做?除了将Foo改为Cython类之外,我还有什么选择?
__cinit__
在整个Cython基类链的类构造时自动调用。对于派生类,您不需要自己调用它(事实上您不能(。Cython基类的__cinit__
也在派生自它的Python类上调用。这是__cinit__
的主要优势-它保证只被调用一次,所以你不能把必须发生的任何初始化放在那里。
__init__
的行为与Python完全相同——调用派生类最多的__init__
函数,然后该函数可能会也可能不会调用基类的__init__
。
例如:
cdef class A:
def __cinit__(self):
...
def __init__(self):
...
cdef class B(A):
def __cinit__(self):
...
def __init__(self):
pass
# in a different file, possibly
class C(B):
def __init__(self):
super().__init__()
你会发现通话顺序是
A.__cinit__
B.__cinit__
C.__init__
B.__init__ (because C.__init__ calls it)
not A.__init__ (because B.__init__ does not call it)
一个常见的建议是:
- 只有当必须做一些工作才能使类有效(例如在C/C++中分配内存(时,才定义CCD_
- 为任意"0"定义CCD_ 8;正常结构";工作-基本上是任何不会导致崩溃的东西,如果它被跳过(意外或故意(