Table of contents
1.
Introduction
2.
How to overload the operators in Python? 
2.1.
Overloading binary + operator in Python
2.2.
Overloading Comparison Operators
2.3.
Overload greater than( > ) operator for two objects
2.4.
Overload less than( < ) operator for two objects
2.5.
Overloading Equality ( = ) operator for two objects.
3.
Magic Functions in Python for Operator Overloading
3.1.
Binary Operators
3.2.
Comparison Operators
3.3.
Assignment Operators
3.4.
Unary Operator
4.
Advantages of Operator Overloading
5.
Frequently Asked Questions
5.1.
What is operator overloading with an example?
5.2.
How does the Plus Operator work in Python?
5.3.
What are the various types of overloading in Python?
6.
Key Takeaways
Last Updated: Jan 19, 2025
Easy

Operator Overloading in Python

Author GAZAL ARORA
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Operator overloading in Python allows customizing the behavior of operators (e.g., +, -) for user-defined objects by overriding special methods like __add__().

Operator Overloading in Python

Operator overloading is a Python feature that allows the same operator to have different meanings depending on the context.

Example:

Let's understand with an example,

# A function to show the use of the + operator for multiple purposes.

# '+' is used to add two integers.
print(2 + 2)

# '+' is used to concatenate two strings.
print("Coding "+"Ninjas")

Output

4
Coding Ninjas

Here, the operator + adds two integers, joins two strings, or merges two lists. It is only possible because the '+' operator is overloaded by the int and str classes.

Similarly, the ‘*’ operator is used to multiply two numbers or repeat a string.

Read About, Divmod in Python and Convert String to List Python.

How to overload the operators in Python? 

In Python, each class defines its behavior for built-in functions and methods. When you pass a class instance to a built-in function or use an operator on the instance, you are actually calling a special method with the relevant arguments.

Consider the following scenario: we have two objects that are physical representations of a class (user-defined data type). When we add two objects with the binary '+' operator, the compiler throws an error since it does not know how to add two objects. As a result, we define a method for an operator, known as operator overloading.

Python provides some special or magic function that is automatically invoked when associated with that operator to perform operator overloading. 

Example:

For example, when we use the + operator, the magic method __add__ is automatically invoked, which defines the action for the + operator.

Note: We can overload all existing operators, but we can't create new ones. 

Let's understand the overloading of multiple operators one by one. 

Must Read, python ord

Also Read About, Python for Data Science

Overloading binary + operator in Python

When we use an operator on user-defined data types, a special or magic function associated with that operator is immediately invoked. Changing the behavior of an operator is as straightforward as changing the behavior of a method or function. Methods are declared in your class, and operators operate by the behavior defined in the methods. 

When we use the ‘+’ operator, the magic function __add__ is immediately performed, which defines the action for the + operator. We may add more significance to the + operator by modifying the code of this magic method.

Let's understand this by modifying the __add__ to add two objects of a user-defined class.

# Function to show how to overload the + operator to add two objects.
class Example:
    def __init__(self, x):
        self.x = x

    # defining the __add__ function to add two objects.
    def __add__(self, o):
        return self.x + o.x

obj1 = Example(2)
obj2 = Example(2)
obj3 = Example("Coding ")
obj4 = Example("Ninjas")

# adding two objects.
print(obj1 + obj2)
print(obj3 + obj4)

Output

4
Coding Ninjas

Here, when you use obj1 + obj2, Python calls obj1.__add__(obj2), which in turn is Example.__add__(obj1, obj2). After that, the addition operation is carried out in the manner that we described.

Overloading Comparison Operators

Python does not restrict operator overloading to simply arithmetic operators. We can also overload comparison operators.

Overload greater than( > ) operator for two objects

Let’s overload greater than( > ) operator for two objects.

When using the ‘>’ operator, the magic function is __gt__.

# Function to overload greater than operator.
class Example:
    def __init__(self, x):
    	self.x = x

    def __gt__(self, o):
        if(self.x > o.x):
            return True
        else:
            return False

obj1 = Example(4)
obj2 = Example(2)

if(obj1 > obj2):
    print("obj1 is greater than obj2")
else:
    print("obj2 is greater than obj1")

Output

obj1 is greater than obj2

 

Must Read Python List Operations

Overload less than( < ) operator for two objects

Let’s now overload less than( < ) operator for two objects.

When using the ‘<’ operator, the magic function is __lt__.

# Function to overload smaller than operator.
class Example:
    def __init__(self, x):
    	self.x = x

    def __lt__(self, o):
        if(self.x < o.x):
            return True
        else:
            return False

obj1 = Example(4)
obj2 = Example(2)

if(obj1 < obj2):
    print("obj1 is less than obj2")
else:
    print("obj2 is less than obj1")

Output

obj2 is less than obj1

 

Overloading Equality ( = ) operator for two objects.

When using the ‘=’ operator, the magic function is __eq__.

# Function to overload greater than operator
class Example:
    def __init__(self, x):
    	self.x = x

    def __lt__(self, o):
        if(self.x == o.x):
            return True
        else:
            return False

obj1 = Example(4)
obj2 = Example(2)

if(obj1 == obj2):
    print("obj1 is equal to obj2")
else:
    print("obj2 is not equal to obj1")

Output

obj2 is not equal to obj1

Magic Functions in Python for Operator Overloading

Operator overloading in Python is achieved using special methods, also known as magic methods. These methods allow customizing the behavior of operators for user-defined classes.

Binary Operators

OperatorMagic Function
+__add__()
-__sub__()
*__mul__()
/__truediv__()
%__mod__()
**__pow__()

Comparison Operators

OperatorMagic Function
==__eq__()
!=__ne__()
<__lt__()
<=__le__()
>__gt__()
>=__ge__()

Assignment Operators

OperatorMagic Function
+=__iadd__()
-=__isub__()
*=__imul__()
/=__itruediv__()

Unary Operator

OperatorMagic Function
-__neg__()
+__pos__()
~__invert__()

Advantages of Operator Overloading

  • Enhances code readability by allowing operators to work intuitively with custom objects.
  • Simplifies complex operations on objects by using standard operators.
  • Enables the reuse of operators for different data types, improving consistency.
  • Facilitates implementing domain-specific languages within Python.
  • Makes user-defined classes behave like built-in types, improving integration.

Frequently Asked Questions

What is operator overloading with an example?

Operator overloading in Python allows customizing operator behavior for user-defined objects, e.g., __add__() enables the + operator for custom classes.

How does the Plus Operator work in Python?

The + operator uses __add__() for addition in numeric types, concatenation in strings/lists, or custom behaviors in user-defined classes.

What are the various types of overloading in Python?

Python supports operator overloading (e.g., __add__) and method overloading using default arguments, as Python does not support traditional method overloading directly.

Key Takeaways

In this article, we learned about operator overloading in Python. We learned that Operator overloading is a Python feature that allows the same operator to have different meanings depending on the context.
We learned how to overload the operators in Python. We also learned about the magic functions of the operators.

Live masterclass