Home Tutorials Python OOP Concepts Operator Overloading
Operator Overloading

Operator Overloading


29. Operator Overloading

Operator overloading allows operators such as + to work with user-defined objects through special methods. This is implemented with methods like __add__().

Syntax

def __add__(self, other):
    pass

Example

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
        
    def __str__(self):
        return f"({self.x}, {self.y})"

p1 = Point(2, 3)
p2 = Point(4, 5)
print(p1 + p2)

Output

(6, 8)
Example

🏋️ Test Yourself With Exercises

Take our quiz on Operator Overloading to test your knowledge.

Browse Quizzes »