我有一个现有的 python 类 X
,我想执行以下操作:
from my_python_module import X
cdef class Y:
cdef X test
但这不是开箱即用的,cdef 只接受 C 类型,而不是 Python 类。任何解决方法?
最佳答案
我不认为你可以 ( http://docs.cython.org/src/userguide/sharing_declarations.html#sharing-extension-types ) 但你可以解决它使用 __cinit__
来断言属性具有正确的类型。扩展类型属性的声明cdef public object x
含义如下:
cdef
被使用 to declare attributes of Cython extension typespublic
使 attribute accessible from Python codeobject
是属性的类型,means that it is a Python objectx
是属性的标识符
在您的 Cython 文件中(例如名为“p.pyx”):
import my_python_module as q
cdef class Y:
cdef int i
cdef public object x # public so it can be accessed from Python
def __cinit__(self, x_):
assert isinstance(x_, q.X)
self.x = x_
和 my_python_module.py
是您定义类 X 的地方:
class X(object):
def __init__(self):
self.i = 1
然后,你可以像这样使用它:
import my_python_module as q
import p
y = p.Y(q.X())
print y.x
print y.x.i
另请注意,cpdef
与 cython == 0.29.22
中的 cdef
相同,cython == 3
(Cython issue 3959 和 warning that cython == 0.29.22
prints 如果使用 cpdef
声明属性;另请参见 changelog entry for that Cython version)。
关于python - Cython:如何将 python 对象作为 cython 类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012348/