Operator Overloading
Learn to overload an operator in Python.
We'll cover the following...
Python permits operator overloading but within certain constraints:
- Overloading the operators for built-in types is not allowed.
- Creating new operators is not allowed.
- Few operators can’t be overloaded, e.g.,
is
,and
,or
andnot
.
Before moving towards operator overloading, let’s first make a scenario. How about making vectors in Python and overloading the operators for them.
✏️ Note: In case, you want to get an overview of what a vector is, click here.
Let’s start implementing a vector.
class Vector():def __init__(self, vector):self.vector = vectordef print(self):print(self.vector)v1 = Vector([1,2])v1.print()
The above code is the basic implementation of vectors in Python. To make a vector, just send a list of numbers to the Vector()
, and you’re good to go. Here we override the function print()
for the Vector
object, which itself calls the built-in print()
to print a vector (list).
Now, we are good to go. Fasten the belts and enjoy the ride of operator overloading.✊
Unary operators
The -
operator
Take -
as a unary operator and do not confuse it with the binary one. It’s an arithmetic negation operator. For example, if x
is ...