2
如何我必須用Cython重寫RMUL?正確覆蓋
例如,這完全在蟒蛇
class PyFoo:
def __init__(self):
self.a = 4
def __mul__(self,b): return b*self.a
def __rmul__(self,b): return self*b
Pynew = PyFoo()
print " Python "
print Pynew*3 # I got 12
print 3*Pynew # I got 12
但是,如果我實現用Cython同樣不起作用,
cclass.pyx
cimport cython
cdef class Foo:
cdef public int a
def __init__(self):
self.a = 4
def __mul__(self,b): return b*self.a
def __rmul__(self,b): return self*b
test.py
import cclass as c
Cnew = c.Foo()
print " Cython "
print Cnew*3 # This works, I got 12
print 3*Cnew # This doesn't
我得到這個錯誤
Traceback (most recent call last):
File "test.py", line 22, in <module>
print 3*Cnew
File "cclass.pyx", line 8, in cclass.Foo.__mul__ (cclass.c:763)
def __mul__(self,b): return b*self.a
AttributeError: 'int' object has no attribute 'a'
我不明白什麼是與使用的問題在用Cython相同的實現RMUL的。
謝謝!是的,我很內疚。我沒有查看文檔,我在谷歌搜索了很多(通常我得到更好的答案,當問題是,一定是行不通的事情)。 我的歉意,再次感謝。 – diego