Classes: Dealing with Complex Numbers

  • + 0 comments
    class Complex(object):
        
        def __init__(self, real, imaginary):
            super().__init__()
            self.real = real
            self.imaginary = imaginary
            
        def __add__(self, no):
            return str(Complex(self.real + no.real, self.imaginary + no.imaginary))
            
        def __sub__(self, no):
            return str(Complex(self.real - no.real, self.imaginary - no.imaginary))
            
        def __mul__(self, no):
            return str(Complex((self.real * no.real) - (self.imaginary * no.imaginary) ,
                     (self.real * no.imaginary) + (self.imaginary * no.real)))
             
        def __truediv__(self, no):
            return str(Complex(((self.real * no.real) + (self.imaginary * no.imaginary)) / (no.imaginary**2 + no.real**2),((self.imaginary * no.real) - (self.real * no.imaginary) ) / (no.imaginary**2 + no.real**2)))
            
        def mod(self):
            return str(Complex((self.real**2 + self.imaginary**2)**0.5,0))