Printing an Object
What happens when you print a pet?
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
rex = Pet("Rex", "dog", 3)
print(rex)<Pet object at 0x1655900>Python doesn't know how a pet should look as text, so it prints the kind of object and where the object is stored in the computer's memory. That number is different from run to run, and it tells you nothing about Rex.
You can tell Python what to show with a method named __str__, with two underscores on each side again. It returns the text for the object, and Python calls it by itself whenever the object has to become text: in print(), in an f-string and in str():
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
def __str__(self):
return f"{self.name} the {self.species}"
rex = Pet("Rex", "dog", 3)
print(rex)
print(f"My pet: {rex}")Rex the dog
My pet: Rex the dogYou don't call __str__ yourself, just as you don't call __init__. The two underscores mark Python's own special methods, which Python calls at the right moment: __init__ when an object is created, __str__ when it has to be shown as text. The names can't be mixed up with methods of your own, such as describe().
__str__ has to return the text. When it prints the text instead, it returns None, and the program prints the text and then ends with TypeError: __str__ returned non-string (type NoneType).
Instructions
- 1
Run the program: it prints
<Pet object at 0x…>. Add a method__str__to the class that returns the pet's name, species and age like this:Rex (dog, 3 years).print(rex)then prints exactly that. Keep the lines that create Rex and Kiwi as they are. - 2
Below, print Kiwi in a sentence with an f-string:
Best friend: Kiwi (parrot, 4 years).