Classes: Dealing with Complex Numbers

  • + 1 comment
    class Complex(object):
        def __init__(self, real, imaginary):
            self.real = real
            self.imaginary = imaginary
            
        def __add__(self, no):
            return Complex(self.real+no.real, self.imaginary+no.imaginary)
            
        def __sub__(self, no):
            return Complex(self.real-no.real, self.imaginary-no.imaginary)
            
        def __mul__(self, no):
            c1 = complex(self.real, self.imaginary)
            c2 = complex(no.real, no.imaginary)
            res = c1 * c2
            
            return Complex(res.real, res.imag)
    
        def __truediv__(self, no):
            c1 = complex(self.real, self.imaginary)
            c2 = complex(no.real, no.imaginary)
            res = c1/c2
            
            return Complex(res.real, res.imag)
    
        def mod(self):
            return Complex(math.sqrt(self.real**2 + self.imaginary**2), 0)