In this Python article, we will explore one of the important topics of python, we will discuss operator overloading. How does operator overloading works and how to extend the existing functionality? This is also an important topic in many interviews. Let’s begin.
Table of Contents
1. What is operator overloading?
In our previous article, we discussed polymorphism via Inheritence. Operator overloading is a section that comes under the compile-time polymorphism.
When we use the same operator to perform different tasks in different scenarios it is known as Operator Overloading.
For example, the operator ‘+’ can be used not only to concatenate two strings but also to add two numbers and merge two lists.
So we are using a single operator but it works differently when used with different data types. How does that happen? It happens because ‘+’ operator is overloaded by int, list, str class, etc and they have modified the implementation as per the requirements of that particular type.
1.1. How does Opeerator Overloading works?
Suppose, we have defined a class with the name ‘Oscar‘ and we have created two instances(objects) with names ‘o1’ and ‘o2’.
If we now try to add these two objects ‘o1‘ and ‘o2‘ with the help of the binary ‘+’ operator, then definitely it will throw an error. This error occurs because there is no in-built function that will help the compiler to add these two objects.
In order to enable such an operation, we will define a method for “+” operator via the process of operator overloading.
NOTE: Python allows us to overload all existing operators but it does not allow the creation of a new operator.
1.2. Overloading the addition operator(+)
There are some special functions or it can be mentioned as some ‘magic function‘ that can be used for operator overloading. Such functions are invoked automatically as soon as they get associated with any specific operator.
For example, when we use + operator, the magic method __add__ is invoked in which the behavior for + operator is defined.