Dunder (magic) methods
Python has special methods that determine how certain objects behave. We call these magic methods or dunder methods. They’re called dunder methods because they start with a double underscore. Sounds like something we’ve just seen? Yes! One example of this is __init__. We won’t go over all of these, but there are a few I’d like to point out.
__str__ dunder method
The first one on the menu is __str__. This method is responsible for displaying an object as text.
Let’s say we do this (assuming we have a cat class).
cat = Cat()
print(cat)
We get something like this:
<__main__.Cat object at 0x7a3520c99430>
This is the default behavior of the built-in __str__ dunder method. If we define our own version of the __str__ method, we can return a human-readable string for print():
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
...