Operator overloading means providing extra meaning beyond the scope of predefined operational meaning. One such example is the ‘+’ operator. It performs addition, join two strings, and add two lists. int class and str class in python while using it for data science overloads the ‘+’ operator and hence it becomes possible.
Sometimes we see that the same built-in function or operator shows different behavior for different class objects. This phenomenon is known as operator overloading.
The technique of Overloading the Operators in Python:
Suppose we possess two objects which are a physical representation of a class and we need to add two objects with binary ‘+’ operator. This will show an error, as the compiler has no idea how to add two objects. So, we define a method for an operator which is there as operator overloading. Overloading can be done on all existing operators, but a new operator cannot be create. In Python some special or magic functions are provide to perform operator overloading. When the specific operator comes into the picture, the magic function is automatically invoke. For example, when we use ‘+’ , the magic method __add__ is invoke automatically.
Overloading binary + Operator in Python:
As we have already discuss, when an operator is there on user-define data type, then a magic function is invoke. As it is easy to change the behavior of the method or function in a similar manner, it is effortless to change the behavior of the operator. Methods are define in classes, and the operators will perform in accordance with the behavior define in methods. Let’s see an example where we have taken ‘+’ operator and given it an extra meaning.
Overloading Comparison Operators:
Overloading equality and less than operators:
Magic methods for Operator Overloading: