2016-11-25 37 views
2

这是我的简化课堂作业: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' 

的错误是明显的,但我没能弄明白,你的帮助,请!

回答

2

您必须Vector类构造函数更改为以下:

class Vector(object): 
    def __init__(self, x, y): 
     self.real = x 
     self.imag = y 

与你的程序的问题是,它定义xy作为属性,而不是realimag,在构造函数中Vector类。

1

这似乎是你忘记了你的初始值设定项。因此,MyComplex的实例没有任何属性(包括realimag)。只需将初始化程序添加到MyComplex即可解决您的问题。

def __init__(self, real, imag): 
    self.real = real 
    self.imag = imag 
+0

还应该指出的是,通过这样做,您可以规避'MyComplex'从'Vector'继承的需求。 – Billylegota

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__函数 '真实' 和 'IMAG'。你应该用self.real和self.imag替换self.x,self.y属性。