python


Operator overloading in Python


In this tutorial we will learn about how to use operator overloading in python.

Python Operator Overloading

Operator overloading allows us to use the same operator having different meaning in different context.It means the operator is overloaded in this process.Same operator is used to perform operation in different structures.


Let's take an example of operator '+'. This operator performs addition function between 2 numbers.But when we use this operator with strings it will concatenate 2 strings.


Example:
>>> 5+3
>>> 8

The above code is for addition of 2 strings

Example2:

# for strings
 string1='Hello'
 string2= World!'
 string3= string1 + string2
 print string3
Output:
Hello World!

The above code will concatenate 2 strings as you can see.
So this is operator overloading.

Overloading the operator '+' in class

To overload '+' operator in class we have to call the function of it. Let's see an example:

Example:
class Calc:
    def __init__(self, a=0, b=0):
        self.a = a
        self.b = b

    def __str__(self):
        return "({0},{1})".format(self.a, self.b)

    def __addition__(self, first):
        a = self.a + first.a
        b = self.b + first.b
        return Calc(a,b)
        
p1=Calc(13,17)
p2=Calc(47,63)
print(p1+p2)     # here '+' operator is overloaded.
(60,80)

In the above code , we define a class named Calc which consist of a function __addition__() is responsible for performing addition.
And then we use to assign the values of a and b which are considered as values to perform operation. We here defined 2 objecs of class Calc in which we perform the addition.And after getting the values of objects then addition between them is performed and here operator overloading works.

Note: Similarly if you want to perform multipication you can use __multiply__() as an function.And same for other operators is also applied.

Overloading comparison operators

We can also overload the comparison operators ,it is not just for arithmatic operations.
Let's take an example, we have to overload > operator:

Example:
# overloading the greater than operator
class Calc:
    def __init__(self, a=0, b=0):
        self.a = a
        self.b = b

    def __str__(self):
        return "({0},{1})".format(self.a, self.b)

    def __greaterthan__(self, other):
        self_mag = (self.a * 3) + (self.b * 3)
        other_mag = (other.a * 3) + (other.b * 3)
        return self_mag > other_mag

p1 = Calc(10,14)
p2 = Calc(-7,-13)
p3 = Calc(41,-21)

# use greater than
print(p1
Output:
True
False
True

In the above example, we overloaded Greater than operator.


Similarly, if you want to overload any other comparison operator you can do that.
For example, if you want to verload less than(>) operator , you can do that by naming function __lessthan__() or what you want.It will also perform the operation in that condition also.