Python Operator Overloading


Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


You have already seen you can use +  operator for adding numbers and at the same time to concatenate strings. It is possible because +  operator is overloaded by both int  class and str  class. The operators are actually methods defined in respective classes. Defining methods for operators is known as operator overloading. For e.g. To use +  operator with custom objects  you need to define a method called __add__  .

Let’s take an example to understand better

Expected Output:

In the above example we have added __add__  method which allows use to use +  operator to add two circle objects. Inside the __add__  method we are creating a new object and returning it to the caller.

python has many other special methods like __add__ , see the list below.

Operator Function   Method Description
+    __add__(self, other)   Addition
*    __mul__(self, other)   Multiplication
-    __sub__(self, other)   Subtraction
%    __mod__(self, other)   Remainder
/    __truediv__(self, other)   Division
<    __lt__(self, other)   Less than
<=    __le__(self, other)   Less than or equal to
==    __eq__(self, other)   Equal to
!=    __ne__(self, other)   Not equal to
>    __gt__(self, other)  Greater than
>=    __ge__(self, other)   Greater than or equal to
[index]    __getitem__(self, index)   Index operator
in    __contains__(self, value)  Check membership
len  __len__(self)   The number of elements
str  __str__(self)   The string representation

Program below is using some of the above mentioned functions to overload operators.

Expected Output:

 

Next lesson is inheritance and polymorphism.


Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


13
Leave a Reply

avatar
6 Comment threads
7 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
PythonGuruPaulRalph Rajko-Nenowadminkyawswa Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Ho
Guest
Ho

In the last program, the line 24 should be fixed. So the output of “c1<c2" is true

leon
Guest
leon

Hi, 2 issues:
1. > __ne___gt__(self, other) Greater than
2. previous comment about: print(c1<c2) and it's output wasn't updated) it should be True))

dato
Guest
dato

Hi, in the last program, the line 27 ends with semicolon. 😀

kyawswa
Guest
kyawswa

Hello,
I am confused about the using of encapsulation in __add__ method. In this method, another_circle’s private variable(__radius) is used. If c2 is instance of Circle class, __add__ method cannot access the private variable from the c2 object. Is that right?
Thanks

kyawswa
Guest
kyawswa

You mean we can access the private variable in the class even different object instance?

Ralph Rajko-Nenow
Guest
Ralph Rajko-Nenow

you didn’t implement __radd__ so sum([circle1,circle2,…]) won’t work

Paul
Guest
Paul

When you define a function such as this one:

def getRadius(self):
return self.__radius

It is mandatory to specify ‘self’ as parameter to the function? If I would remove that would it work?

PythonGuru
Admin

Yes, it is required.