Lesson 2 of 10
An object that describes itself
- 11 min
- 5 checks
- 3 hints
- Go to task
Goal
repr for developers, str for users
Explanation
Print an object of a class you just wrote and you'll see something like <Money object at 0x7f3a…>: the class name and a memory address, and nothing about what's inside. That's exactly what will show up in your logs and error messages when you need them most.
Python has two ways to turn an object into text. __str__ is for users: it returns readable text like 50 SAR, and it's what print and str() call. __repr__ is for developers: it returns clear, unambiguous text, ideally the very line that creates the object, Money(50, 'SAR'). Put !r after each field so the string '50' shows up in quotes and can't be mistaken for the number 50.
The trap is that lists and dicts always show their items with repr, even inside print. Write only __str__, print a list, and the cryptic addresses are back. If you don't write __str__, Python falls back to __repr__, but never the other way around, so if you only write one, make it __repr__.
Your task
Give Money a __repr__ method that returns Money(50, 'SAR') and a __str__ method that returns 50 SAR.
Checks
5 checks- repr matches the constructor call
- repr tells a string from a number
- str is human-readable
- A list shows the repr of its items
- eval(repr(m)) rebuilds the object