Nearby lessons
109 of 159Python - Operator Overloading
- 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:
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.
Internal Working of the + Operator
Whenever we use an operator with objects, Python internally calls the corresponding magic method.
Suppose we write:
Explanation
Internally, Python converts b1 + b2 into:
Role of self and other
b1is available asself.b2is available asother.
Using these references, we can define exactly how two Book objects should be added.
Demo Program: Overloading the + Operator
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.
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
Explanation
When e * t executes, Python internally calls e.__mul__(t).
Inside the method:
selfrefers to the Employee objecte, soself.salaryis 500.otherrefers to the TimeSheet objectt, soother.daysis 25.
The method returns 500 * 25, which is 12500.
Operator to Magic Method Mapping
| Expression | Internal Method Call |
|---|---|
a + b | a.__add__(b) |
a - b | a.__sub__(b) |
a * b | a.__mul__(b) |
a / b | a.__truediv__(b) |
a > b | a.__gt__(b) |
a <= b | a.__le__(b) |
- 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