Operator Overloading
Overload the + operator for a custom class using __add__.
IntermediateTopic: Object-Oriented Programs
Python Operator Overloading Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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)
Understanding Operator Overloading
Implementing __add__ allows the + operator to work naturally with Vector instances.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.