Python复数乘法

时间:2016-11-25 19:39:02

标签: python-2.7 vector complex-numbers

这是我的简化课程作业:

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'

错误很明显,但我没弄清楚,请帮助你!

3 个答案:

答案 0 :(得分:3)

您必须将Vector类中的构造函数更改为以下内容:

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

您的计划存在的问题是,它在x类的构造函数中将yreal定义为属性,而不是imagVector

答案 1 :(得分:1)

您似乎忘记了初始化程序。因此,MyComplex的实例没有任何属性(包括realimag)。只需将初始化程序添加到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属性。

相关问题