Cython扩展类型属性误解
我正在尝试让一个Cython类里的成员可以被Python访问。这个成员的类型是基本类型,比如说 int
(整数)或者 float
(浮点数)。
根据我在文档中看到的,你可以使用属性来让Python访问底层的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
但是当我使用第二种方法时,它却不奏效。这个变量从来没有被更新过。我是不是漏掉了什么,或者没有完全理解呢?
谢谢你的帮助。
1 个回答
1
你已经找到了答案,使用 property
是正确的做法。
public
属性可以在类的方法外部访问,而 private
属性只能在类的方法内部使用。
不过,即使是 C++ 中定义的 public
属性,在 Python 中也无法直接访问。如果想让 Python 能够使用 private
或 public
属性,就需要通过 property
来暴露它们。