Command Palette

Search for a command to run...

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

A Vector that works with print, ==, +, * and sum

Remove __radd__ and run again to read the TypeError that sum() raises. Then add __sub__.

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 Vector that works with print, ==, +, * and sum
Sign in to run this example in your browser.

Expected output

Vector(3, 4) <3, 4> <3, 4>
[Vector(3, 4), Vector(1, 2)]
<4, 6>
<6, 8> <6, 8>
<14, 16>
True False False
2
5.0
False True
Vector(3, 4) and <3, 4>
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'