TL ; DR:
Give a class a __str__ method that returns a string. Then print shows that string for the object.
class Cat:
def __init__(self, name):
self.name = name
def __str__(self):
return "Cat named " + self.name
print(Cat("Tom")) # Cat named Tom
Full lesson:
Python turns an object into text before it prints it. On its own, it only knows the class name and a memory address:
<__main__.Cat object at 0x7f3a2c1e5d90>
That text tells you nothing about the cat.
A __str__ method fixes this. It returns the text that stands for the object. Python calls it for you.
It does so whenever the object becomes text. print(tom) calls it. So does str(tom), and so does an f-string like f"I have {tom}".
__str__ takes only self. It must return the text, not print it. The caller decides where the text goes.
Your task
The Dog class below has a name and an age. Add a __str__ method to it.
It returns the name, then " is ", the age and " years old". The code at the bottom prints two dogs.
Expected output:
Rex is 3 years old
Bella is 5 years oldFree plan: 30 tutor messages. Premium is unlimited.
