这是我的简化课堂作业:Python的复数乘法
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
class MyComplex(Vector):
def __mul__(self, other):
return MyComplex(self.real*other.real - self.imag*other.imag,
self.imag*other.real + self.real*other.imag)
def __str__(self):
return '(%g, %g)' % (self.real, self.imag)
u = MyComplex(2, -1)
v = MyComplex(1, 2)
print u * v
这是输出:
"test1.py", line 17, in <module>
print u * v
"test1.py", line 9, in __mul__
return MyComplex(self.real*other.real - self.imag*other.imag,
self.imag*other.real + self.real*other.imag)
AttributeError: 'MyComplex' object has no attribute 'real'
的错误是明显的,但我没能弄明白,你的帮助,请!
还应该指出的是,通过这样做,您可以规避'MyComplex'从'Vector'继承的需求。 – Billylegota