首页 > 解决方案 > Cython,无法访问魔术算术函数中的类成员

问题描述

考虑以下测试类:

cdef class Test:
cdef int a

def __cinit__(self, a):
    self.a = a

def __add__(self, other):
    return Test(self.a + other.a)

编译并执行

import test    
t = test.Test(1)
t2 = test.Test(2)

t3 = t + t2

产生以下错误

traceback (most recent call last):
  File "test.py", line 19, in <module>
    t3 = t + t2
  File "test.pyx", line 285, in test.Test.__add__
    return Test(self.a + other.a)
AttributeError: 'test.Test' object has no attribute 'a'

为什么会这样?到目前为止,以类似的方式实现其他魔法功能,如复制,效果很好。

标签: pythonpython-3.xcython

解决方案


推荐阅读