Python的复数乘法
问题描述:
这是我的简化课堂作业: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'
的错误是明显的,但我没能弄明白,你的帮助,请!
答
您必须Vector类构造函数更改为以下:
class Vector(object):
def __init__(self, x, y):
self.real = x
self.imag = y
与你的程序的问题是,它定义x
和y
作为属性,而不是real
和imag
,在构造函数中Vector
类。
答
这似乎是你忘记了你的初始值设定项。因此,MyComplex
的实例没有任何属性(包括real
或imag
)。只需将初始化程序添加到MyComplex
即可解决您的问题。
def __init__(self, real, imag):
self.real = real
self.imag = imag
答
def __init__(self, x, y):
self.x = x
self.y = y
...
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'
您还没有属性,在__init__函数 '真实' 和 'IMAG'。你应该用self.real和self.imag替换self.x,self.y属性。
还应该指出的是,通过这样做,您可以规避'MyComplex'从'Vector'继承的需求。 – Billylegota