Q47: How does Operator Overloading function using dunder methods?
Operator symbols map directly to internal magic methods (dunder methods). Custom classes implement methods like __add__() (+), __sub__() (-), __eq__() (==), or __getitem__() ([]) to define custom operator evaluation.
Operator Overloading Vector Addition
class Vector:
def __init__(self, x, y):
self.x, self.y = x, 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})" 💡 Overriding __add__ enables adding two Vector objects using standard + operators.
Key Takeaways
- Maps operators (
+,-,==) to special methods (__add__,__sub__,__eq__). - Right-hand variants (
__radd__) handle fallback arithmetic when left operands do not support the operation.
Knowledge Check
Which magic method handles indexing lookups obj[key] on custom classes?