解决Cython扩展类中__getattr__的非标准行为问题
解决方案
针对Cython中cdef类__getattr__拦截所有属性访问的问题,有两种高效的兼容方案,无需逐个判断属性:
方案1:在__getattr__中模拟原生Python的调用逻辑
Cython的cdef类会把__getattr__当作__getattribute__使用,拦截所有属性访问。我们可以在__getattr__里先尝试通过父类的__getattribute__获取已定义属性,失败后再返回默认值,这样同时兼容原生Python和Cython:
# 原生Python版本 class Test: field = 24 def __getattr__(self, name): return 42 # Cython版本(兼容原生) cdef class Test: field = 24 def __getattr__(self, name): try: # 调用父类的__getattribute__获取已存在的属性,不会触发当前__getattr__ return super().__getattribute__(name) except AttributeError: # 属性不存在时返回默认值 return 42
如果是cdef实例属性,需要声明为public让Python层可见:
cdef class Test: cdef public int field # 声明为public,让Python可以访问 def __init__(self): self.field = 24 def __getattr__(self, name): try: return super().__getattribute__(name) except AttributeError: return 42
方案2:统一使用__getattribute__替代__getattr__
直接重写__getattribute__,在其中处理属性查找失败的情况。这种方式在原生Python和Cython中行为完全一致,无需区分环境:
# 原生Python和Cython通用 class Test: # Cython中改为cdef class Test: field = 24 def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return 42
这种方式的逻辑是:先尝试获取属性,失败则返回默认值,和原生Python中__getattr__的效果完全相同,同时在Cython中也能正确区分已定义属性和未定义属性。
注意事项
- 若使用cdef私有属性(未加
public),Python层无法直接访问,这类属性不会触发__getattr__或__getattribute__的逻辑,需要通过类方法暴露。 - 避免在
__getattribute__或__getattr__中再次调用self.name,否则会触发无限递归,必须通过object.__getattribute__或super().__getattribute__来获取属性。
内容的提问来源于stack exchange,提问作者Szymon Łopaciuk
相关产品推荐
相关产品推荐

