Operator Overloading

Overload the + operator for a custom class using __add__.

PythonIntermediate
Python
# Program to demonstrate operator overloading

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)

Output

Vector(4, 6)

Implementing add allows the + operator to work naturally with Vector instances.