python - Cython:如何将 python 对象作为 cython 类的属性

标签 python c class binding cython

我有一个现有的 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含义如下:

在您的 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

另请注意,cpdefcython == 0.29.22 中的 cdef 相同,cython == 3(Cython issue 3959warning that cython == 0.29.22 prints 如果使用 cpdef 声明属性;另请参见 changelog entry for that Cython version)。

关于python - Cython:如何将 python 对象作为 cython 类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012348/

相关文章:

Python不在for循环中打印文件内容

python - python中字符串的算术[MINUS]

c - 扩展 rand() 的范围时改进 "randomness"

c++ - 当有多个构造函数时如何设置默认构造函数

python - 使用 Cython 和 "next"编译

python - 为什么 Manager().dict() 只更新了一层?

c - 我是否必须在函数内分配返回的字符串?

c - 如何处理此错误?(检测到堆栈粉碎已中止(核心已转储))

C++ - 错误 : 'list' does not name a type (list object as member variable in class)

c++ - 计算成员值时 vector 的奇怪问题