Lesson · Python Data Model & Special Methods
Operator Overloading
55 min readOperator Overloading
Operator overloading lets objects define arithmetic and comparison semantics through special methods. It is most effective when the operator meaning is unsurprising for the domain.
Learning goals
- Explain how
a + bdispatches: the left operand's__add__first, then the right operand's__radd__if it returnsNotImplemented. - Write
__add__for theVectordataclass so two vectors produce a new vector with summed coordinates. - Say why a binary method returns
NotImplementedfor foreign types instead of raising or guessing. - Describe how
+=picks__iadd__when present and otherwise falls back to__add__plus a rebind. - Judge when operator overloading fits the domain, using
Vectoraddition as the clear case.
Mental model
The concepts form one dispatch chain. The expression always starts with the left operand's method, hands the work to the right operand's reflected method when the first declines, and raises TypeError when neither side handles it. In-place and comparison operators are the same chain with different method names, and the worked example plugs into only one link of it by defining __add__.
Mental model
read it top to bottom
a + b → a.__add__(b), then b.__radd__(a) if the left side returns NotImplemented a += b → __iadd__ first, else plain __add__ plus a rebind a == b → __eq__; dataclass(frozen=True) generates it from the fields no handler → NotImplemented on both sides, then TypeError
Core idea
Operator overloading maps syntax onto methods: a + b calls __add__ on the left operand, offers the reflected __radd__ on the right when that returns NotImplemented, and raises TypeError when neither handles the pair. The worked example's frozen Vector adds coordinates and returns a new Vector, so the operator reads exactly like arithmetic on numbers. The design test is whether the symbol's meaning is the obvious one for the domain: + for vectors is natural, + for two unrelated business objects is not.
Arithmetic special methods
Arithmetic special methods map the math symbols onto dunders: + to __add__, - to __sub__, * to __mul__, and so on, each receiving two operands and returning a result object. Vector.__add__ sums x and y into a new frozen Vector, which is why Vector(1, 2) + Vector(3, 4) prints Vector(x=4, y=6). An unsupported operand should return NotImplemented so Python can try the other side's reflected method.
Comparison methods
Comparison methods back ==, !=, <, <=, >, and >= through __eq__, __lt__, and their siblings. @dataclass(frozen=True) generates __eq__ for Vector field by field (and __hash__ because the class is frozen), so two vectors with equal coordinates compare equal with no hand-written code. Ordering methods are not generated unless order=True is set, so < on the example still raises TypeError.
Reflected operators
Reflected operators handle the case where the left operand cannot: Python tries a.__add__(b), and if that returns NotImplemented it calls b.__radd__(a). Each forward method has a mirrored name (__radd__, __rsub__, __rmul__, and so on), which is what lets a custom type cooperate with a built-in on the left, as in 2 * vector. If both sides decline, the operation raises TypeError.
In-place operators
In-place operators back +=, -=, and friends through __iadd__, __isub__, and so on. When __iadd__ is missing, Python falls back to __add__ and rebinds the name to the new object, which is the only possible outcome for the frozen Vector since its attributes cannot change after construction. A mutable type can implement __iadd__ to update itself and return self instead.
Appropriate use
Overloading fits when the operator's meaning is the obvious one for the domain, which makes Vector(1, 2) + Vector(3, 4) read as coordinate addition. It misfires when the symbol suggests a different operation than it performs, when readers must consult the class to decode an expression, or when a plain named method would state the intent better. When in doubt, keep the method name: path.append(step) says more than an overloaded += with hidden behavior.
Walkthrough
Vectoris a@dataclass(frozen=True)with twofloatfields, so instances are immutable and compare by both coordinates;__add__starts withisinstance(other, Vector)and returnsNotImplementedfor anything else.- The successful branch builds a brand-new
Vector(self.x + other.x, self.y + other.y), soVector(1, 2) + Vector(3, 4)printsVector(x=4, y=6)and neither operand changes. - Nothing else is overloaded:
Vectorhas the dataclass-generated__eq__, but-and<raiseTypeError, andvector + 1does too because the reflected lookup finds no handler oninteither. - Predict before running: the exact line
Vector(x=4, y=6), and whatvector + 1does at runtime.
Experiments to try
- Call
Vector(1, 2).__add__((3, 4))directly and confirm it returnsNotImplemented; then runVector(1, 2) + (3, 4)and read theTypeErrorthat follows. - Add
__rmul__that scales a vector by a number and test2 * vectoragainstvector * 2; explain which side's method serves each expression. - Add
__sub__following the__add__pattern and checkVector(3, 4) - Vector(1, 2); also confirm both operands keep their original values. - With the frozen class, run
v = Vector(1, 2)thenv += Vector(3, 4); explain why it works with no__iadd__and whethervis the same object afterwards.
Common mistakes
- Returning
Noneor raising from a binary method instead of returningNotImplemented:Nonesilently becomes the result of the expression, and an exception stops Python from ever trying the right operand's reflected method. - Mutating an operand inside
__add__: callers expect+to build a new object, so in-place changes make aliases shift under their feet; mutation belongs in__iadd__. - Defining
__add__without__radd__and expecting1 + vectorto work: same-type expressions hide the gap until the operand order flips. - Overloading a symbol with a meaning that is not obvious from the domain, so readers must consult the class definition to decode an expression.
Practice: Easy
- Run the worked example and record the printed line; then check
Vector(1, 2) == Vector(1, 2)and name the method the frozen dataclass generated for it. - Run
v = Vector(1, 2)followed byv += Vector(3, 4); explain which method served the+=and whyvends up as a new object. - Run
Vector(1, 2) + 1and record theTypeError; explain why__add__returningNotImplementeddid not prevent an error in this case.
Practice: Medium
- Add
__sub__and__rmul__toVector, then verifyVector(3, 4) - Vector(1, 2)and2 * Vector(1, 2)both produce new vectors with the right coordinates. - Define
__lt__comparing(x, y)tuples and sort a small list of vectors; explain whyVector(1, 9) < Vector(2, 0)is true under that rule. - Take a small
Moneyclass and decide operator by operator (+,*,<) whether overloading helps or hurts; record one justified overload and one rejected candidate with the reason.
Practice: Hard
- Design a
Durationtype that overloads+(sum of durations) and*(multiply by a number only), add__rmul__so3 * dworks, and test every invalid operand path. - Build a failure lab:
__add__returningNoneand the silentNoneresult;__add__raisingTypeErrordirectly so a reflected method never gets its turn; mutatingselfinside__add__and the alias corruption it causes. Explain each mechanism and its fix. - Connect this lesson to expression evaluation: with
__add__and__mul__defined, tracea + b * cand list the method calls in order, then explain which operand's reflected method gets a chance when the left one declines.
Lesson checklist
- I can trace
a + bthrough__add__,NotImplemented, and__radd__in order. - I can implement
__add__on theVectordataclass and confirm the result is a new object. - I can explain what
+=does on the frozen class (no__iadd__, so__add__plus a rebind). - I can argue for or against overloading a given operator based on its domain meaning.
Remember
Operator overloading routes syntax to methods: `a + b` tries `__add__` on the left, `__radd__` on the right when the left returns `NotImplemented`, and raises `TypeError` when both decline; `+=` prefers `__iadd__` and otherwise rebuilds through `__add__`. The worked example overloads exactly one operator on a frozen `Vector` and lets the dataclass supply equality, which shows the safe shape: return new objects, hand foreign operands `NotImplemented`, and overload only symbols whose meaning is obvious for the domain.
Interview angles
What is the main purpose of **Arithmetic special methods**?+
+, -, * and the other math operators call methods such as __add__, __sub__, and __mul__. Vector.__add__ checks its operand, returns Vector(x=4, y=6) for Vector(1, 2) + Vector(3, 4), and returns NotImplemented when the other operand is not a Vector.
What should you pay attention to when using **Comparison methods**?+
==, <, and the other comparison operators call __eq__, __lt__, and their siblings. @dataclass(frozen=True) generates __eq__ (and __hash__) for Vector from its fields; ordering operators such as < are not generated unless order=True, so they still raise TypeError.
How does **Reflected operators** fit into this lesson?+
When the left operand's method returns NotImplemented, Python calls the mirrored method on the right operand (__radd__ for +). The worked example defines only __add__, so vector + 1 fails after both paths decline; adding __radd__ to a class is what makes expressions such as 2 + vector work.
What is the difference between returning `NotImplemented` and raising an exception from `__add__`?+
NotImplemented is a signal: Python then offers the operation to the right operand's reflected method and raises TypeError only if nobody handles it. Raising (or returning None) never gives that second chance: the exception propagates, or None silently becomes the result of the expression.