【发布时间】:2014-01-09 05:37:36
【问题描述】:
我有一个现有的 python 类X,我想做以下事情:
from my_python_module import X
cdef class Y:
cdef X test
但这不是开箱即用的,cdef 只接受 C 类型,而不接受 Python 类。有什么解决方法吗?
【问题讨论】:
标签: python c class binding cython
我有一个现有的 python 类X,我想做以下事情:
from my_python_module import X
cdef class Y:
cdef X test
但这不是开箱即用的,cdef 只接受 C 类型,而不接受 Python 类。有什么解决方法吗?
【问题讨论】:
标签: python c class binding cython
我认为你不能 (http://docs.cython.org/src/userguide/sharing_declarations.html#sharing-extension-types) 但你可以使用__cinit__ 来断言该属性具有正确的类型。扩展类型属性的声明cdef public object x含义如下:
cdef 被使用 to declare attributes of Cython extension types
public 使 attribute accessible from Python code
object 是属性的类型,means that it is a Python object
x 是属性的标识符在您的 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 中不受支持,如果属性是用@987654344 声明的) @;另见changelog entry for that Cython version)。
【讨论】:
object 可以用来分配任何python 对象?
我会使用这样的东西:
cdef class SomeCls:
cdef object _x
def __cinit__(self, x_):
self._x = x_
property x:
def __get__(self):
return self._x
def __set__(self, x_):
self._x = x_
在公开外部结构或类的属性时,上述内容特别有用。请参阅此处的示例: wrapping C++
【讨论】: