Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Mini Project: Playing Cards with Dunders

18 min 45 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 6 of 6 · View course roadmap
Step 1

Learn the idea

Dunder (double-underscore) methods let your objects plug into Python's own syntax:

  • __str__ — what print(obj) shows
  • __eq__ — makes == meaningful for your type
  • __lt__ — enables < and therefore sorted()
  • __len__ — makes len(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).

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +45 XP

Blank · autosaved

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.

Target output
3
4
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. Which dunder controls what print(obj) displays?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path