Projects/operator_overloading.py

14 lines
397 B
Python

# Example of operator overloading in Python - defining a custom class with overloaded __add__ operator
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)
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2 # Uses overloaded __add__ method
print(v3.x, v3.y) # 6 8