repr and str

Print an object with no special methods and you get something like <__main__.Plain object at 0x10f3a2>. That tells you nothing.

  • __repr__ is for developers. Make it look like the code that rebuilds the object: Temperature(21.5).
  • __str__ is for users. print() and str() use it, and fall back to __repr__ if it's missing.

The surprise: containers always show the repr of their items. So print([t]) shows [Temperature(21.5)] even though print(t) shows 21.5°C.

If you write only one, write __repr__. It shows up in the debugger, in logs, in error messages, and in test failures, which print got and want with repr. A good repr makes bugs obvious.

Run it, then delete __str__ and see what print(t) does.