A container, ordering and a callable
Try list(p), min(p) and p[::-1]. All work because the class follows the container protocol.
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
3 rain wind ['rain', 'waves']
True False
playing rain
playing waves
playing wind
['rain', 'waves', 'wind'] ['wind', 'waves', 'rain']
False
[Version('1.2.0'), Version('1.2.10'), Version('1.10.0')]
True True
Version('1.10.0')
Hello, Asha! True