Python › Magic Methods & Operator Overloading

How do you overload arithmetic operators like + and - using __add__ and __sub__?

Intermediate

Answer

Defining __add__(self, other) lets instances of your class respond to the + operator, and similarly __sub__, __mul__, __truediv__, etc. for other operators. Python calls left.__add__(right) first; if that returns NotImplemented, it tries right.__radd__(left) as a fallback, supporting mixed-type operations.
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})'

print(Vector(1,2) + Vector(3,4))  # Vector(4, 6)
Real-world example A physics simulation's Vector3D class overloads +, -, *, and dot() so simulation code reads like natural math instead of verbose method calls.

Common follow-ups: What does __radd__ handle that __add__ doesn't?;How do you support in-place addition with __iadd__?