How does Overloading Operators work in Python?

PythonServer Side ProgrammingProgramming

We know that we can use +  operator for adding numbers and at the same time to concatenate strings. This is possible because +  operator is overloaded by both int  class and str  class. The operators are basically methods defined in respective classes. Defining methods for operators is known as operator overloading. For e.g. To use +  operator with custom objects we need to define a method called __add__  .

Example

Following code make it easy to understand how operator overloading works

import math
class Circle:
     def __init__(self, radius):
        self.__radius = radius
     def setRadius(self, radius):
        self.__radius = radius
     def getRadius(self):
        return self.__radius
     def area(self):
        return math.pi * self.__radius ** 2
     def __add__(self, another_circle):
        return Circle( self.__radius + another_circle.__radius )
c1 = Circle(3)
print(c1.getRadius())
c2 = Circle(6)
print(c2.getRadius())
c3 = c1 + c2 # This is because we have overloaded + operator by adding a method  __add__
print(c3.getRadius())

Output

This gives the output

3
6
9

Modifying the behavior of an operator so that it works with user-defined types is called operator overloading. For every operator in Python there is a corresponding special method, like __add__. For more details, see docs.python.org/ref/specialnames.html.


raja
Published on 18-Jan-2018 14:00:21
Advertisements