Cython扩展类型属性误解

Cython extension types attributes misunderstanding

本文关键字:误解 属性 类型 扩展 Cython      更新时间:2023-10-16

我试图为cython类中的一个成员授予python访问权限。成员类型是基本的(例如intfloat

正如我在文档中所读到的,您可以使用属性来访问底层C++成员:

cdef class myPythonClass:
   # grant access to myCppMember thanks to myMember
   property myMember:
      def __get__(self):
        return self.thisptr.myCppMember # implicit conversion
      # would somehow be the same logic for __set__ method

现在这就行了。

但是,据我所知,对于基本类型,您可以只使用扩展类型。在这种情况下,您可以使成员public可访问和/或可写。您不需要属性:

 cdef class myPythonClass:
    cdef public int myCppMember # direct access to myCppMember

但当我使用第二个选项时,它不起作用。该变量永远不会更新。是我遗漏了什么,还是我没有完全理解?

感谢您的投入。

您已经找到了解决方案,使用property是最好的方法。

public属性可以在类方法之外访问,而private属性只能由类方法使用。

但是,即使是在C++级别定义的public属性也不能从Python访问。使用property公开privatepublic属性将使其可用于Python。