Python

Operator Overloading in Python

Overloading corresponds to the tendency of a method or an operator to act in multiple ways in the sense of programming, based on the parameters provided to the technique or the operands on which the operator operates. Operator Overloading means that prolonged meaning is given above their predefined functional significance.  Python operators function for built-in classes, but for various types, the very same operator acts differently. We’ll see how we might do operator overloading in Python in this guide.

For instance, the + operator can add two numbers mathematically, combine two lists, or concatenate strings. Here is a simple python program to show a glimpse of the + operator used for addition and concatenation.

Well, what comes if we use these operators for objects in a user-defined class? Let us take the following program that attempts to simulate a spot in the 2-D scheme of dimensions. Below, you can already see that because Python did not understand how to join 2 coordinates instances, a Type Error is generated.

We can accomplish this task in Python via the operator overloading, but first of all, let’s understand the special methods.

Special Magical Methods

Class methods starting with the double underscore are classified in Python as special methods or magic functions. The functions that are used to carry out specific activities. The usual methods we describe for a class are not such functions. One of them would be the __init_() function we mentioned above. Any time we build a new object in that class, it’s called. We will render our class-compliant to built-in functions via magic functions. In Python, there are several other special functions.

Binary or Mathematical Operators

Here are the details of the magic functions for overloading the python binary or mathematical operators.

Relational or Comparison Operators

Below are the details of the magic functions for overloading the python comparison or relational operators.

Assignment Operators

Here are the details of some magic functions for overloading the assignment operators in python code.

Now, it’s time to glimpse a couple of sample codes when we use the magic methods mentioned above and overload certain operators.

Overload the Binary or Mathematical Operators

Example 01: Addition Operator
You will have to enforce the __add_() method in the class to overload the + operator. Great duty arrives with great strength. Inside this method, you could do anything you want. But it is much more rational to return the ‘Coord’ object of the coordinate sum.

When you tried c1 + c2, Python actually calls its magic .__add__() method as c1.__add__(c2) or Coord.__add__(c1,c2).

Example 02: Multiplication Operator
Likewise, you can even overload several binary operators using magic functions. In the same above example, while overloading the multiplication operator, we get 2, 6 as our answer to the magic function.

Example 03: Subtraction Operator
Using the subtraction operator, we got -1, -1 as our answer.

Example 04: Power Operator
We overloaded the power operator while using the power magic function; we got 1, 8.

Example 05: Modulus Operator
Overloading the modulus operator, we have used the __mod__ magic function to get the modulus.

You can also use the other mathematical operators, e.g., division and floor division operator, for overloading.

Overload the Comparison Operators

Python doesn’t restrict the overloading of operators to just binary or arithmetic operators. We are also able to overload comparison operators.

Example 01: Less than Operator
Assume we required less than the ‘<‘ symbol in our ‘Coord’ class to be implemented. Let us compare the value of these arguments from the source and yield the answer. As usual, it can be applied. We have three objects, and we are comparing them in print statements. As a result, we will get that object c1 is less than c2, so it outputs True. On the other hand, c2 and c1 are more excellent than c3; that’s why both False output.

Example 02: Not Equal to Operator
Now overloading the Not Equal (!=) comparison operator, you will get True in the case of the first and second print statement because it satisfies the condition that both the objects are not equal. On the other hand, object 1 yields the same as object 3, which does not meet the requirement of Not equal. That is why the third print statement outputs False as a result.

Example 03: Greater than or Equal to Operator
Let’s try the same example for overloading the greater than or equal to operator. In the case of the first print statement, we have 2 >= 13, which is not true; that is why it yields False. In the second and third print statements, we got 13>=2 and 2>=2, respectively. Both are True as they satisfy the condition of greater than or equals to.

Try the other comparison operators, e.g., more significant than, equal to, ‘less than or equal to,’ in your code as well.

Overload the Assignment Operators

Have a look at an example of assignment operator overloading. We are taking a similar example with the overloading of the ‘-=’ assignment operator. We have defined two objects having values of y and z coordinates. First object c1 is passing its values to ‘self.y’ and ‘self.z’ variables, respectively. On the other hand, the object c2 is passing its values to ‘other.y’ and ‘other.z’.

Object c1 has values of self.y=1 and self.z=1 right now. The object c2 values ‘other.y = -2’ and ‘other.z = -3’ has been passed to subtracted from object c1 values. As a result, c1 – c2 results self.y – other.y = 1-(-2) and self.z – other.z = 1-(-3). The calculated result, which is 3 and 4, has been saved into ‘self.x’ and ‘self.z’ due to the assignment operator of ‘=.’ On print, this code will output the result of object c1, which has two variables self.y = 3 and self.z = 4.

Conclusion

We try to cover all the operators in your code for a better understanding of Operator Overloading.

About the author

Aqsa Yasin

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.