Lesson 5: __str__ — how an object prints itself
What happens when you print an object? Without preparation you get odd text like <__main__.Dog object at 0x...>. In this lesson we meet __str__ — a magic method that teaches the object to present itself nicely.
__str__ is the object's name tag. Without it, print() shows a boring identifier; with it — the object introduces itself exactly how you choose.
- __str__
- A magic method that returns a string — print() calls it automatically when the object is printed.
- magic (dunder) method
- A method with two underscores on each side — Python calls it automatically at special moments.