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:

Loading editor…

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.

Loading editor…

Internal Working of the + Operator

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

Suppose we write:

Loading editor…

Explanation

Internally, Python converts b1 + b2 into:

Loading editor…

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

Loading editor…

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.

Loading editor…

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

Loading editor…

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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.