这是我的简化课程作业:
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'
错误很明显,但我没弄清楚,请帮助你!
答案 0 :(得分:3)
您必须将Vector类中的构造函数更改为以下内容:
class Vector(object):
def __init__(self, x, y):
self.real = x
self.imag = y
您的计划存在的问题是,它在x
类的构造函数中将y
和real
定义为属性,而不是imag
和Vector
。
答案 1 :(得分:1)
您似乎忘记了初始化程序。因此,MyComplex
的实例没有任何属性(包括real
或imag
)。只需将初始化程序添加到MyComplex
即可解决您的问题。
def __init__(self, real, imag):
self.real = real
self.imag = imag
答案 2 :(得分:1)
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__函数中归因于'real'和'imag'。你应该用self.real和self.imag替换self.x,self.y属性。