Python Operator Overloading

In this tutorial, we will learn about operator overloading in Python with the help of examples.

In Python, we can change the way operators work for user-defined types.

For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading.


Example: + Operator Overloading

Suppose if we have a class called Complex that represents complex numbers, we could overload the + operator to add two Complex objects together. For example,

class Complex:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    # add two objects
    def __add__(self, other):
        return self.real + other.real, self.imag + other.imag

obj1 = Complex(1, 2)
obj2 = Complex(3, 4)
obj3 = obj1 + obj2
print(obj3)

# Output: (4, 6)

In the above example, we have used the + operator to add two Complex objects a and b together.

The __add__() method overloads the + operator to add the real and imaginary parts of the two complex numbers together and returns a new Complex object with the resulting values.

The __str__() method returns a string representation of the complex number in the form a + bj.


Overloading Comparison Operators

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Here's an example of how we can overload the < operator to compare two objects the Person class based on their age:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # overload < operator
    def __lt__(self, other):
        return self.age < other.age

p1 = Person("Alice", 20)
p2 = Person("Bob", 30)

print(p1 < p2)  # prints True
print(p2 < p1)  # prints False

Output

True
False

Here, __lt__() overloads the < operator to compare the age attribute of two objects.

The __lt__() method returns,

  • True - if the first object's age is less than the second object's age
  • False - if the first object's age is greater than the second object's age

Note: We can define similar methods to overload the other comparison operators. For example, __gt__() to overload > operator, __eq__() to overload == operator and so on.


Python Special Functions

Class functions that begin with double underscore __ are called special functions in Python.

The special functions are defined by the Python interpreter and used to implement certain features or behaviors.

They are called "double underscore" functions because they have a double underscore prefix and suffix, such as __init__() or __add__().

Here are some of the special functions available in Python,

Function Description
__init__() initialize the attributes of the object
__str__() returns a string representation of the object
__len__() returns the length of the object
__add__() adds two objects
__call__() call objects of the class like a normal function

Advantages of Operator Overloading

Here are some advantages of operator overloading,

  • Improves code readability by allowing the use of familiar operators.
  • Ensures that objects of a class behave consistently with built-in types and other user-defined types.
  • Makes it simpler to write code, especially for complex data types.
  • Allows for code reuse by implementing one operator method and using it for other operators.
Did you find this article helpful?