Classes: Dealing with Complex Numbers

  • + 0 comments
    import math
    
    class Complex(object):
        def __init__(self, real, imaginary):
            self.real = real
            self.imaginary = imaginary
            self.c = complex(*(real, imaginary))
    
        @staticmethod
        def to_complex(no):
            return complex(*(no.real, no.imaginary))
            
        def __add__(self, no):
            c = self.c + Complex.to_complex(no)
            return Complex(c.real, c.imag)
     
        def __sub__(self, no):
            c = self.c - Complex.to_complex(no)
            return Complex(c.real, c.imag)
    
        def __mul__(self, no):
            c = self.c * Complex.to_complex(no)
            return Complex(c.real, c.imag)
    
        def __truediv__(self, no):
            c = self.c / Complex.to_complex(no)
            return Complex(c.real, c.imag)
    
        def mod(self):
            c = math.sqrt(self.c.real ** 2 + self.c.imag ** 2)
            return Complex(c.real, c.imag)