Python复数乘法

Python Complex Number Multiplication

这是我简化的 class 作业:

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 中的构造函数更改为以下内容:

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

您的程序的问题在于它在 Vector 的构造函数中将 xy 定义为属性,而不是 realimag class.

看来您忘记了初始化程序。因此,MyComplex 的实例没有任何属性(包括 realimag)。只需向 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__ 函数中没有属性 'real' 和 'imag'。您应该将 self.x、self.y 属性替换为 self.real 和 self.imag。