Start learning free

LESSON 645 OF 673 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in Python: The __str__ Method

Lesson Read the full explanation

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 old
STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING

    Printing Objects in Python, explained

    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:

    1. Below __init__, start a method named __str__ that takes only self.
    2. Inside it, return an f-string built from self.name and self.age. An f-string turns the number into text for you, so no str() 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, str and 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 a TypeError.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free