Nearby lessons

109 of 159

Python - Operator Overloading

📌 What You Will Learn
  • Understand what operator overloading is
  • Know the special magic methods used for operator overloading
  • Overload the + operator with __add__()
  • Overload the * operator with __mul__()
  • Overload comparison operators with __gt__() and __le__()

What Is Operator Overloading?

We can use the same operator for multiple purposes. This concept is called Operator Overloading.

For example, the + operator is already overloaded for several built-in Python types:

  • For numbers, + performs arithmetic addition.
  • For strings, + performs concatenation.
  • For lists, + performs list concatenation.

Python also allows programmers to define how operators should work with their own class objects. This is done with special methods called Magic Methods.

The Book Example

Consider a class named Book where each object contains the number of pages.

Suppose we create two Book objects and try to add them using the + operator:

🐍Code Cell
1class Book:
2 
3 def __init__(self, pages):
4 self.pages = pages
5 
6 
7b1 = Book(100)
8b2 = Book(200)
9 
10print(b1 + b2)
Output
TypeError: unsupported operand type(s) for +: 'Book' and 'Book'

Why Does the TypeError Occur?

Python already knows how to use + with built-in types such as integers, floats, strings, and lists.

But Python does not automatically know what + should mean for two Book objects. Should it add their page counts? Should it combine the objects? Python cannot decide automatically, so it raises a TypeError.

To solve this problem, we have to overload the + operator for the Book class.

Magic Methods

Python provides special methods for operator overloading. These special methods are commonly called:

  • Magic Methods
  • Special Methods
  • Dunder Methods

The word dunder means double underscore.

🐍Code Cell
1__add__()
2__sub__()
3__mul__()
4__truediv__()
Output
No output captured.

Internal Working of the + Operator

Whenever we use an operator with objects, Python internally calls the corresponding magic method.

Suppose we write:

🐍Code Cell
1b1 + b2
Output
No output captured.

Explanation

Internally, Python converts b1 + b2 into:

🐍Code Cell
1b1.__add__(b2)
Output
No output captured.

Role of self and other

  • b1 is available as self.
  • b2 is available as other.

Using these references, we can define exactly how two Book objects should be added.

Demo Program: Overloading the + Operator

🐍Code Cell
1class Book:
2 
3 def __init__(self, pages):
4 self.pages = pages
5 
6 def __add__(self, other):
7 return self.pages + other.pages
8 
9 
10b1 = Book(100)
11b2 = Book(200)
12 
13print(b1 + b2)
Output
300

Explanation

The __add__() method tells Python what should happen when the + operator is used between two Book objects.

When b1 + b2 executes, Python internally calls b1.__add__(b2). Inside the method, self.pages is 100 and other.pages is 200, so the result is 300.

Important Magic Methods for Operator Overloading

Operator Magic Method Example
+__add__()a + b
-__sub__()a - b
*__mul__()a * b
/__truediv__()a / b
//__floordiv__()a // b
%__mod__()a % b
**__pow__()a ** b
+=__iadd__()a += b
-=__isub__()a -= b

Comparison Operator Overloading

Python allows us to overload comparison operators for programmer-defined class objects.

For every comparison operator, Python provides a corresponding magic method:

  • The > operator uses __gt__().
  • The <= operator uses __le__().
  • The == operator uses __eq__().
  • The != operator uses __ne__().
Operator Magic Method
<__lt__()
<=__le__()
>__gt__()
>=__ge__()
==__eq__()
!=__ne__()

Demo Program: Overloading > and <= for Student Objects

The following program overloads the > and <= operators for Student objects. The comparison is performed based on the students' marks.

🐍Code Cell
1class Student:
2 
3 def __init__(self, name, marks):
4 self.name = name
5 self.marks = marks
6 
7 def __gt__(self, other):
8 return self.marks > other.marks
9 
10 def __le__(self, other):
11 return self.marks <= other.marks
12 
13 
14print("10>20 =", 10 > 20)
15 
16s1 = Student("Durga", 100)
17s2 = Student("Ravi", 200)
18 
19print("s1>s2=", s1 > s2)
20print("s1<s2=", s1 < s2)
21print("s1<=s2=", s1 <= s2)
22print("s1>=s2=", s1 >= s2)
Output
10>20 = False
s1>s2= False
s1=s2= False

Explanation

s1 > s2 internally calls s1.__gt__(s2), which compares 100 with 200 and returns False.

s1 <= s2 internally calls s1.__le__(s2), which checks whether 100 is less than or equal to 200 and returns True.

The < and >= comparisons work through Python's reflected rich-comparison protocol: s1 < s2 is answered by asking whether s2 > s1 is true, and s1 >= s2 is answered by asking whether s2 <= s1 is true.

Multiplication Operator Overloading

Python allows us to overload the multiplication operator * for programmer-defined objects.

The magic method corresponding to the * operator is __mul__().

In this example, we use an Employee class and a TimeSheet class to calculate the employee's monthly salary based on the salary value and the number of working days.

Complete Program: Employee * TimeSheet

🐍Code Cell
1class Employee:
2 
3 def __init__(self, name, salary):
4 self.name = name
5 self.salary = salary
6 
7 def __mul__(self, other):
8 return self.salary * other.days
9 
10 
11class TimeSheet:
12 
13 def __init__(self, name, days):
14 self.name = name
15 self.days = days
16 
17 
18e = Employee("Durga", 500)
19t = TimeSheet("Durga", 25)
20 
21print("This Month Salary:", e * t)
Output
This Month Salary: 12500

Explanation

When e * t executes, Python internally calls e.__mul__(t).

Inside the method:

  • self refers to the Employee object e, so self.salary is 500.
  • other refers to the TimeSheet object t, so other.days is 25.

The method returns 500 * 25, which is 12500.

Operator to Magic Method Mapping

Expression Internal Method Call
a + ba.__add__(b)
a - ba.__sub__(b)
a * ba.__mul__(b)
a / ba.__truediv__(b)
a > ba.__gt__(b)
a <= ba.__le__(b)
📝 Key Takeaways
  • Operator overloading allows the same operator to work with programmer-defined class objects
  • Every operator has a corresponding magic (dunder) method
  • b1 + b2 internally calls b1.__add__(b2)
  • e * t internally calls e.__mul__(t)
  • Comparison operators use __gt__(), __le__(), __eq__(), and other comparison magic methods

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8