Search⌘ K
AI Features

Operator Overloading

Explore how to implement operator overloading in Python to customize behavior for user-defined classes like vectors. Learn to overload unary operators, vector addition, and scalar multiplication with proper handling of edge cases using reflection methods to maintain clean, robust code.

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 and not.
svg viewer

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.

Python 3.10.4
class Vector():
def __init__(self, vector):
self.vector = vector
def 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 55 ...