Search code examples
python-2.7vectorcomplex-numbers

Python Complex Number Multiplication


This is my simplified class assignment:

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

This is the output:

"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'

The error is clear, but I failed to figure it out, your assistance please!


Solution

  • You must change the constructor in Vector class to the following:

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

    The problem with your program was that it defined x and y as attributes, not real and imag, in the constructor for Vector class.