Why printing an object shows nonsense
Python turns an object into text before it prints it. For a class you wrote, it knows only the class name and where the object lives in memory:
class Cat:
def __init__(self, name):
self.name = name
tom = Cat("Tom")
print(tom)
This prints something like the line below. The number after 0x changes from run to run:
<__main__.Cat object at 0x7d6634092ed0>
That text says nothing about the cat. A class can say better by defining __str__.
The __str__ method
__str__ takes only self and returns a string that stands for the object. You never call it yourself. Python calls it whenever the object has to become text:
print(tom)str(tom)- an f-string such as
f"I have {tom}"
The two underscores on each side mark a method Python calls for you, like __init__.
Return the text, don't print it
The most common mistake is to put a print inside __str__. The method must return the text, and the caller decides where it goes. A __str__ that prints and returns nothing gives None, and Python refuses it:
class Bad:
def __str__(self):
print("hi")
print(Bad())
The text "hi" is printed first, then the call fails with TypeError: __str__ returned non-string (type NoneType).
Another trap: __str__ is used by print and str, but not when an object sits inside a list. Printing [rex] for the Dog below still shows the address form, because a list shows its items with a different method (__repr__).
Building the text
The returned value has to be a string. Inside it you can join pieces with +, but then every number must go through str() first. With self.age equal to 3, self.name + " is " + self.age raises TypeError: can only concatenate str (not "int") to str. An f-string avoids the problem: it converts each value in braces to text itself, and the whole label reads like the output it produces.
The exercise: a Dog that prints well
The Dog class has a name and an age. The task is to add a __str__ that returns the name, then " is ", the age and " years old". The steps:
- Below
__init__, start a method named__str__that takes onlyself. - Inside it, return an f-string built from
self.nameandself.age. An f-string turns the number into text for you, so nostr()call is needed.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
print(rex)
print(bella)
Running it prints:
Rex is 3 years old
Bella is 5 years old
The same method also works with str and inside f-strings: str(rex) gives Rex is 3 years old, and f"I have {rex}" gives I have Rex is 3 years old.
A second method: __repr__
Python has another method for turning an object into text, __repr__. It is meant for programmers: ideally it shows how to build the object again. Containers use it for their items, which is why a list of dogs shows __repr__ text and not the __str__ sentence. If a class defines __repr__ as return f"Dog({self.name!r}, {self.age})", then print([rex]) shows [Dog('Rex', 3)], while print(rex) still uses __str__. For this lesson __str__ is all you need.
Key takeaways
- Without
__str__, printing an object shows the class name and an address. __str__(self)returns the text; it doesn't print it.print,strand f-strings all call it for you.- Numbers inside the text need an f-string or
str(); joining a string and an int with+raises aTypeError.
