Operator Overloading in Python

What is operator overloading ?

When operator behave differently depending on the arguments passed to it, it is called operator overloading. This is special case of polymorphism.

If we apply + operator to 2 strings they are concatinated, if we apply it to numbers they are added and if we do it with lists, second list gets appended to first list.

Why should we use ?

If we create custom objects and if we want to support common operations such as addition, subtractions etc. We have to overload that operator in our class.

Lets take example of custom object to represent complex number –

class Complex(object):
    def __init__(self, real_part, imaginary_part=0.0):
        self.real = real_part
        self.imag = imaginary_part
 
    def __str__(self):
        return '(%g, %g)' % (self.real_part, self.imaginary_part)

If we create two objects of type Complex and try to add them

a = Complex(1,5)
b = Complex(3,10)

c = a + b

Output - TypeError: unsupported operand type(s) for +: 'Complex' and 'Complex'

We get this error because python dont know how to add the objects of type Complex. For this we have to overload the + oprator in our Complex class. To achieve this we have to implement __add__ method in Complex class and return the result of addition operation from this function.

class Complex(object):
    def __init__(self, real, imag=0.0):
        self.real = real
        self.imag = imag

   # + operator overloaded
   def __add__(self, other):
       return Complex(self.real + other.real,
       self.imag + other.imag) 

   def __str__(self):
       return '(%g, %g)' % (self.real, self.imag)

Now lets again check the result of previous addition operation –

a = Complex(1,5)
b = Complex(3,10)

c = a + b
print(c)

Output - 
(4, 15)

So now python knows how to add objects of type Complex. In this way we can overload other operators too. We have to implement specific special method in our class for that. There are special functions for every operator. You can find complete list in python documentation.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s