Dunder Methods Part 2 — Operator Overloading and Container Behavior
~22 min · dunder, operator-overloading, len, getitem, iter, contains
Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
Operator overloading — what each symbol calls
Every operator in Python maps to a dunder. + is __add__. - is __sub__. * is __mul__. < is __lt__. The full list is in the data model. Implementing them lets you write v1 + v2 on your custom Vector class. Reflected versions (__radd__, etc.) handle the case where your class is on the right side of an operator with a different type on the left.
Container dunders — len, getitem, contains, iter
__len__ makes len(obj) work. __getitem__ makes obj[i] work. __contains__ makes x in obj work. __iter__ makes for x in obj work. If you implement __getitem__ with integer indices, you get free iteration too — Python falls back to __getitem__(0), __getitem__(1), ... until IndexError.
__bool__ — truthiness for your objects
Without __bool__, Python uses __len__ if defined (length 0 is falsy) or treats every instance as truthy. Define __bool__ when neither default is right for your type. The method must return a bool.
__call__ — making your instance act like a function
Define __call__ and you can write my_instance(args). Used everywhere — class-based decorators, function objects with state, callable strategies. We saw it in the decorators track.
Principle: Operator overloading is great when the operations have a natural meaning for your type (Vector + Vector, Money + Money). It's bad when the operation is forced or ambiguous (User + User?). The bias: if a reader can't predict what a + b does just from knowing the types, don't overload.
Build a class Polynomial representing a polynomial as a list of coefficients (constant term first). Implement __repr__ (e.g. 'Polynomial([1, 0, 2])' meaning 1 + 0x + 2x²), __add__ (returns a new Polynomial with coefficients added pairwise; pad shorter with zeros), __call__(x) to evaluate the polynomial at x. Test addition and evaluation: (Polynomial([1, 2, 3]) + Polynomial([0, 1]))(2) should be 1 + 3*2 + 3*4 = 19.
Progress
Progress is local-only — sign in to sync across devices.