A Vector that works with print, ==, +, * and sum
Remove __radd__ and run again to read the TypeError that sum() raises. Then add __sub__.
Special methods (dunder methods) such as __repr__, __eq__, __len__, __iter__, __add__ and __call__ are hooks that Python calls for you when your object is printed, compared, measured, looped over, added or called. Implementing them makes your own classes behave like built-in types.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Money with amount and currency. Add __repr__, __eq__, and __add__ (only for the same currency; otherwise return NotImplemented). Print Money(5, "INR") + Money(7, "INR").
Write a class Team with a list of names, supporting len(team), "Asha" in team and for name in team. Print each.
Write a class Multiplier whose objects are called like functions: triple = Multiplier(3), then triple(5) returns 15. Use it with list(map(triple, [1, 2, 3])).
Explain it without notes
What are special (dunder) methods and who calls them?
What is the difference between __repr__ and __str__?
Why does defining __eq__ make a class unhashable, and how do you fix it?
How does sum([v1, v2]) work with a custom class, and why is __radd__ needed?
Expected output
Vector(3, 4) <3, 4> <3, 4>
[Vector(3, 4), Vector(1, 2)]
<4, 6>
<6, 8> <6, 8>
<14, 16>
True False False
2
5.0
False True
Vector(3, 4) and <3, 4>
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'