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

Dunder Methods & the Python Data Model

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

Learn the idea

Why does len("abc") work? Because str implements __len__. Python's operators and built-ins are a thin layer over dunder (double-underscore) methods — implement them and your own classes plug straight into the language:

  • __repr__ — how the object prints (aim for something a developer could paste back into code)
  • __add__ — powers a + b
  • __eq__ — powers == (by default Python compares identity, not value!)
  • __len__, __getitem__, __contains__ — make objects sliceable, iterable and in-testable

This is called the data model, and it's the most Pythonic idea in the language: instead of inventing .equals() or .plus() methods, you teach your objects to speak Python's native vocabulary.

Where you'll use this

pathlib overloads / to join paths, NumPy overloads every operator for arrays, Django models compare by value — Python's most loved libraries feel native precisely because they implement the data model instead of inventing method names.

Common mistakes

  • Defining __eq__ without thinking about __hash__ — Python sets __hash__ to None, and your objects can no longer live in sets or dict keys. Implement both or use @dataclass(frozen=True).
  • Returning a plain tuple from __add__ instead of a new instance of your class — addition should stay closed over the type.
  • Writing __repr__ that hides information: aim for eval-able output like Vector(4, 6), not '<Vector object>'.

Pro tip

Implement __repr__ on every class you write, first thing. Debugging a list of '' is misery; a list of Order(id=7, total=99.5) reads itself.

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

Build a Vector class with x and y. Implement __repr__ returning Vector(x, y), __add__ for coordinate-wise addition, and __eq__ for value equality. Print Vector(1, 2) + Vector(3, 4), then print Vector(1, 2) == Vector(1, 2).

Target output
Vector(4, 6)
True
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. Without __eq__, what does obj1 == obj2 compare?
2. Which dunder does a + b call?
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