Reference link: Operator overloading in Python
Operator overload python
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.
Welcome to the Python operator overloading tutorial. As we already know Python Class, today we will learn another interesting feature of object-oriented python.
Python Operator Overloading
Python Operator overloading enables us to use mathematical, logical and bitwise operators on python objects just like any primitive data type.
Python operator overloading allows us to use mathematical, logical, and bitwise operators on Python objects 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.
For example, you can use the + operator to easily add two numbers 3 and 5, which is 3 +5. 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.
But what if you want to add two circles (objects of class Circle) and make a circle with twice the radius? Or, what if you want to add two Cartesian grid points to produce another point with the same "+" operator? Python operator overloading allows you to perform operations just like those operations.
Python Operator Overloading Example
Now, let’s see an example of overloading mathematical operator.
Now, let's look at an example of overloaded mathematical operators.
class 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.
Lines 1 to 4 represent the declaration and construction method definition of the GridPoint class. Let's take a look at rows 6 and 7.
def 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.
When we use the'+' operator as a mathematical addition operation, the add() method is called implicitly.
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.
Therefore, if you want to add two objects of the GridPoint class, you must redefine this method. Therefore, here we need to create another instance of the GridPoint class, the value of x is the sum of x in the two GridPoint instances near the'+' operator, and the value of y is also the two GridPoint instances around'' The sum of y in. +'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 9 to 12 define the str() method, which is called when we try to print the object. This is also a built-in method. But we will overload this method so that it prints in the 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.
On lines 14 and 15, we created two objects of GridPoint, point1 and point2. Now, look at line 16. Use the'+' operator to add two instances of the GridPoint class and assign them to another instance of GridPoint. Python operator overloading can help you do this. So don't be surprised when line 17 shows the output shown in the figure below.
List of Mathematical Operators
Here is a list of operators which can be overloaded and used with python operator overloading in a similar way.
This is a list of operators that can be overloaded and can be used with python operator overloading in a similar way.
OperatorDescriptionMethod+Addition__add__(self, other)–Subtraction__sub__(self, other)*Multiplication__mul__(self, other)/True Division__truediv__(self, other)//Floor Division__floordiv__(self, other)%Remainder__mod__(self, other)**Power__pow__(self, other)&Bitwise AND__and__(self, other)|Bitwise OR__or__(self, other)^Bitwise XOR__xor__(self, other)
Operator description method + addition __add __ (self, other)-subtraction __sub __ (self, other) * multiplication __mul __ (other) / 真师__truediv __ (self, other) // Floor department __floordiv __ (self, other)% Yu __mod __ (self, other) ** Power __pow __ (self, other) and bitwise with __ and __ (self, other) | bitwise or __ or __ (Self, other) ^ bitwise exclusive OR __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.
Relational operators are overloaded in a very similar way in python. But the difference is that these operators usually return true/false instead of another instance of the object. Let us look at an example.
class 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
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.
Look at line 6, the "greater than" operator has been loaded. If the operand on the left is greater than the operand on the right, the regular'>' operator will return true. We will use this property to compare two instances of the GridPoint class.
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’.
Then in line 17, we compare objects of the GridPoint class to obtain a boolean value, which will determine whether the first object has a larger'x' value. In this case, when 3 is greater than -1, the relational operator returns true. The result is that 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.
This is a list of relational operators that can be overloaded in the same way.
OperatorDescriptionMethod>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)
Operator description method> better 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) == equals __eq __ (self, other)! = Not equal to __ne __ (self, others)
That’s all for today about operator overloading in python. Hope to be with you with more tutorials very soon. Happy Coding!
Today is about operator overloading in python. Hope there will be more tutorials with you soon. Happy coding!
Reference: Python.org Docs
Reference: Python.org documentation
Translated from: https://www.journaldev.com/14637/python-operator-overloading
Operator overload python