Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.7 — Special Methods: The Python Data Model
Python · Example 2 of 2

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.

01

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").

02

Write a class Team with a list of names, supporting len(team), "Asha" in team and for name in team. Print each.

03

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

01

What are special (dunder) methods and who calls them?

02

What is the difference between __repr__ and __str__?

03

Why does defining __eq__ make a class unhashable, and how do you fix it?

04

How does sum([v1, v2]) work with a custom class, and why is __radd__ needed?

A container, ordering and a callable
Sign in to run this example in your browser.

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