Operator Overloading in Python

Overload the + operator for a custom class using __add__.

IntermediateObject-Oriented ProgramsExample 11 of 25
operator-overloading.py
1# Program to demonstrate operator overloading
2
3class Vector:
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8 def __add__(self, other):
9 return Vector(self.x + other.x, self.y + other.y)
10
11 def __repr__(self):
12 return f"Vector({self.x}, {self.y})"
13
14v1 = Vector(1, 2)
15v2 = Vector(3, 4)
16print(v1 + v2)

Output

Vector(4, 6)

What's going on

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

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.