【问题标题】:Cython: how to make an python object as a property of cython classCython:如何将 python 对象作为 cython 类的属性
【发布时间】: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


    【解决方案1】:

    我认为你不能 (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 中不受支持,如果属性是用@987654344 声明的) @;另见changelog entry for that Cython version)。

    【讨论】:

    【解决方案2】:

    我会使用这样的东西:

    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++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2013-06-05
      • 2017-11-14
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      相关资源
      最近更新 更多