Operator Overloading in Python
Operator overloading means defining what an operator like +, -, or == actually does when used on instances of a custom class, by implementing the matching dunder method. Python already does this itself for built-in types — + means addition for numbers but concatenation for strings — and the same mechanism is fully available for any class you write.
Each operator maps to a dunder method
+ calls __add__, - calls __sub__, == calls __eq__, and so on.
Define the matching method to control the operator
__add__(self, other) controls exactly what instance + other does.
The method returns whatever the operator should produce
Python doesn’t assume anything about the result.
Overloaded operators should feel intuitive
Mirroring how + or == behaves for built-in types keeps the class easy to use correctly.
No dunder method means no support
Using an operator without its matching method defined raises a TypeError.
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 __str__(self): return f"Vector({self.x}, {self.y})" v1 = Vector(1, 2)v2 = Vector(3, 4)print(v1 + v2)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.