28
Operator overloading in python
Hi everyone,
In this post I want to explain the concept of operator overloading in python.
In simple terms, it allows you to define what an operator does depending on it's argument.
Let's say that you are implementing a library to perform matrix operation. Instead of implementing a function to add 2 matrix you can overload a +
operator instead. This will make your library much easier to use.
The code
class matrix:
def __init__(self,value):
self.value=value
def __add__(self,other):
result =[[0 for i in range(len(self.value[0]))] for x in range(len(self.value))]
# iterate through rows
for i in range(len(self.value)):
# iterate through columns
for j in range(len(self.value[0])):
result[i][j] = self.value[i][j] + other.value[i][j]
return result
x = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
y = [[9,8,7],
[6,5,4],
[3,2,1]]
print(matrix(x)+matrix(y))
Breaking it down
__init__
- It initializes the object. Nothing special
__add__
-This is where the overloading of the +
operator occurs. Within this function you have to implement how to add those numbers and that's it. It is how you overload operator in python.
Operator that can be overloaded
Binary Operators:
+
= __add__(self, other)
β
= __sub__(self, other)
*
= __mul__(self, other)
/
= __truediv__(self, other)
//
= __floordiv__(self, other)
%
= __mod__(self, other)
**
= __pow__(self, other)
>>
= __rshift__(self, other)
<<
= __lshift__(self, other)
&
= __and__(self, other)
|
= __or__(self, other)
^
= __xor__(self, other)
Comparison Operators :
<
= __lt__(self, other)
>
= __gt__(self, other)
<=
= __le__(self, other)
>=
= __ge__(self, other)
==
= __eq__(self, other)
!=
= __ne__(self, other)
Assignment Operators :
-=
= __isub__(self, other)
+=
= __iadd__(self, other)
*=
= __imul__(self, other)
/=
= __idiv__(self, other)
//=
= __ifloordev__(self, other)
%=
= __imod__(self, other)
**=
= __ipow__(self, other)
>>=
= __irshift__(self, other)
<<=
= __ilshift__(self, other)
&=
= __iand__(self, other)
|=
= __ior__(self, other)
^=
= __ixor__(self, other)
Unary Operators:
β
= __neg__(self, other)
+
= __pos__(self, other)
~
= __invert__(self, other)
This is the list of operators you can overload in python along with the name of the method you have to use
Operator overloading is a powerful feature of python and can be very useful however you should not misuse it because it can create confusing code that is hard to read. I hope you learned something new. If you have enjoyed this one, make sure to read my previous post
Thanks for reading <3
28