Operator Overloading

Learn about operator overloading in Python.

Overloading operators in Python

Operators in Python can be overloaded to operate in a certain user-defined way. Whenever an operator is used in Python, its corresponding method is invoked to perform its predefined function. For example, when the + operator is called, it invokes the special function, __add__, in Python, but this operator acts differently for different data types. For example, the + operator adds the numbers when it is used between two int data types and merges two strings when it is used between string data types.

Run the code below for the implementation of the + operator for integers and strings.

Press + to interact
print(5 + 3) # adding integers using '+'
print("money" + "maker") # merging strings using '+'

Overloading operators for a user-defined class

When a class is defined, its objects can interact with each other through the operators, but it is necessary to define the behavior of these operators through operator overloading.

We are going to implement a class that represents a complex number.“ A complex number consists of a real part and an ...

Access this course and 1400+ top-rated courses and projects.