Operator overloading in python: Python Arithmetic on Complex numbers

Write a sample program to perform Addition(+), Subtraction(-), Multiplication(*),Division(/) between complex numbers. And also perform Mod(underRoot(Square(real)+square(imaginary))) of complex number. 
from math import pow
class complex:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
    def __add__(self, other):
        return complex(self.real+other.real, self.imag+other.imag)
    def __sub__(self, other):
        return complex(self.real-other.real, self.imag-other.imag)
    def __mul__(self, other):
        return complex(self.real*other.real-self.imag*other.imag, self.real*other.imag+self.imag*other.real)
    def __div__(self, other):
            return self.__mul__(complex(other.real, -1*other.imag)).__mul__(complex(1.0/(other.mod().real)**2, 0))
        except Exception as e:
            print e
            return None
    def mod(self):
        return pow(self.real**2+self.imag**2, 0.5)
    def __str__(self, precision=2):
        return str(("%."+"%df"%precision)%float(self.real))+('+' if self.imag>=0 else '-')+str(("%."+"%df"%precision)%float(abs(self.imag)))+'i'

print "Enter real and imaginary part of complex No - 1(separeated by space)" 
A = complex(*map(float, raw_input().strip().split()))
print "Enter real and imaginary part of complex No - 2(separeated by space)" 
B = complex(*map(float, raw_input().strip().split()))

print "Addition: " + str(A+B)
print "Subtraction: " + str(A-B)
print "Multiplication: " + str(A*B)
print "Division: "+ str(A/B)
print "Modulas of complex Number A: " + str(A.mod())
Sample output:-
Enter real and imaginary part of complex No - 1
3 4
Enter real and imaginary part of complex No - 2
2 3
Addition: 5.00+7.00i
Subtraction: 1.00+1.00i
Multiplication: -6.00+17.00i
Division: 1.38-0.08i
Modulas of complex Number A: 5.0

Python provides ability to override inbuilt arithmetic methods like __add__(),__sub__(), etc methods. It is similar to overriding __str__() method to print formatted output(like we have done in above code).For more detail refer this.

What happens internally when we perform + operation between two objects(Remember primitive integer is object in python)?- When we sum two objects in Python, like
a + b
the __add__ method of the a object is called: a.__add__(b)
it means that we can control the result of a sum of two objects by modifying or defining our own __add__ method.


  1. Replies
    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

Previous Post Next Post