Operator Overloading in Python
Overload the + operator for a custom class using __add__.
IntermediateObject-Oriented ProgramsExample 11 of 25
operator-overloading.py
Run in browser1# Program to demonstrate operator overloading23class Vector:4 def __init__(self, x, y):5 self.x = x6 self.y = y78 def __add__(self, other):9 return Vector(self.x + other.x, self.y + other.y)1011 def __repr__(self):12 return f"Vector({self.x}, {self.y})"1314v1 = 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.