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

import math
class Circle:
def area(self):
return math.pi * self.__radius ** 2
c1 = Circle(3)
c2 = Circle(6)
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.

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