Mini Project: Playing Cards with Dunders
Lesson 6 of 6 · View course roadmap
Learn the idea
Dunder (double-underscore) methods let your objects plug into Python's own syntax:
__str__— whatprint(obj)shows__eq__— makes==meaningful for your type__lt__— enables<and thereforesorted()__len__— makeslen(obj)work
This is why len("abc"), len([1,2]) and len(my_deck) can all work — each type implements __len__. Design your classes to feel native and they become a joy to use.
Where you'll use this
len(df), dict[key], obj1 == obj2, with open(...) — every piece of 'built-in' Python syntax is a dunder call under the hood. Pandas and NumPy feel native precisely because they implement these.
Common mistakes
- Defining __str__ but returning a non-string → TypeError when printing.
- Implementing __eq__ without thinking about __hash__ — custom-equal objects may behave oddly in sets/dicts.
- Calling dunders directly (
x.__len__()) — always use the built-in (len(x)); it's faster and idiomatic.
Pro tip
Implement __repr__ first on every class — it's what the debugger, lists and error messages show. Aim for output a developer could paste back into Python: Card(rank=7).
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +45 XP
Create a class Deck that stores a list of numbers passed to __init__, implements __len__, and a method top() returning the last number. Create Deck([2, 9, 4]), print its length and its top card.
3 4
__len__ must return len(self.cards); top() returns self.cards[-1].
class Deck:
def __init__(self, cards):
self.cards = cards
def __len__(self):
return len(self.cards)
def top(self):
return self.cards[-1]
d = Deck([2, 9, 4])
print(len(d))
print(d.top())
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.