Welcome to the tutorial on Python Operator Overloading. As we have already learnt about Python Class, we are going to learn another interesting feature of object oriented python today.
Table of Contents
Python Operator Overloading
Python Operator overloading enables us to use mathematical, logical and bitwise operators on python objects just like any primitive data type.
For example, you can easily add two numbers 3 and 5 with + operator, i.e 3 + 5. And the result is 8.
But what if you want to add two circles (object of a Circle class) and make a circle having twice the radius? Or what if you want to add two cartesian grid points to yield another point with the same ‘+’ operator? Python operator overloading allows you to perform operations just like those.
Python Operator Overloading Example
Now, let’s see an example of overloading mathematical operator.
Copyclass GridPoint: #Line: 1, Declaring a class def __init__(self, x, y): self.x = x self.y = y #Line: 4 def __add__(self, other): # Equivalent of + operator return GridPoint(self.x + other.x, self.y + other.y) def __str__(self): #Line: 12, returns the attributes when the object is printed string = str(self.x) string = string + ", " + str(self.y) return string #Line: 12 point1 = GridPoint(3, 5) #Line: 14 Creating a grid point point2 = GridPoint(-1, 4) #Line: 15, Creating another point point3 = point1 + point2 #Line: 16, Add two points using __add__() method print(point3) #Line: 17, Print the attributes using __str__() method
Lines 1 to 4 indicates the declaration of the class
GridPoint and definition of constructor method. Let’s have a look at lines 6 and 7.
Copydef __add__(self, other): # Equivalent of + operator return GridPoint(self.x + other.x, self.y + other.y)
When we use ‘+’ operator as mathematical addition operation, the
__add__() method is implicitly called.
So, if we are to add two objects of the class GridPoint, we must re-define this method. So, here we need to create another instance of GridPoint class whose value of x is the summation of x in the two GridPoint instances around the ‘+’ operator and value of y is also the summation of y in the two GridPoint instances around the ‘+’ operator.
Lines 9 to 12 defines the
__str__() method which is called when we try to print the object. That’s also a built in method. But we are going to overload the method so that it prints in our specified format.
Lines 14 and 15, we’ve created two objects of GridPoint, namely point1 and point2. Now, watch Line 16. Two instances of the class GridPoint class are added using ‘+’ operator and assigned as another instance of GridPoint. Python operator overloading helps you do this. So, don’t get surprised when the 17th line shows an output like below image.
List of Mathematical Operators
Here is a list of operators which can be overloaded and used with python operator overloading in a similar way.
|/||True Division||__truediv__(self, other)|
|//||Floor Division||__floordiv__(self, other)|
|&||Bitwise AND||__and__(self, other)|
||||Bitwise OR||__or__(self, other)|
|^||Bitwise XOR||__xor__(self, other)|
Overloading Relational Operators in Python
Relational operators are overloaded in a very similar way in python. But the difference is, those operators often return true/false instead of another instance of the object. Let’s work with an example.
Copyclass GridPoint: def __init__(self, x, y): self.x = x self.y = y def __gt__(self, other): # Overloading the greater than operator return self.x > other.x # Returns true if value of x in the left operand is greater than that in the right one. Returns false otherwise def __str__(self): string = str(self.x) string = string + ", " + str(self.y) return string point1 = GridPoint(3, 5) point2 = GridPoint(-1, 4) if point1 > point2: # Compares with the overloaded __gt__() method print('point1 is greater than point2') else: print('point1 is not greater than point2')
Look at line 6, where the ‘greater than’ operator has been loaded. The conventional ‘>’ operator returns true if the operand in the left side of it is greater than the right one. We are going to use this property to compare two instances of class GridPoint.
Then in line 17, we are comparing the objects of the class GridPoint to obtain a boolean type value which will determine whether the first object has the greater value of ‘x’. In this case, the relational operator returns true as 3 is greater than -1. As a result the program prints ‘point1 is greater than point2’.
More Relational Operators in python
Here is a list of relational operators that can be overloaded in the same way.
|>||Greater than||__gt__(self, other)|
|>=||Greater than or equal to||__ge__(self, other)|
|<||Less than||__lt__(self, other)|
|<=||Less than or equal to||__le__(self, other)|
|==||Equal to||__eq__(self, other)|
|!=||Not equal to||__ne__(self, other)|
That’s all for today about operator overloading in python. Hope to be with you with more tutorials very soon.
Reference: Python.org Docs