← All lessons

__str__: how an object looks in print

Sign in · Sign up

Lesson 10.9

Without __str__ an object prints ugly: <__main__.Hero object at 0x...>. The __str__ method sets what you see in print and in str(...):

class Hero:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

    def __str__(self):
        return f"{self.name}: {self.hp} HP"

print(Hero("Mia", 100))
  • __str__ only returns a string: a print inside it would show the text, but the object itself would still be shown the old way;
  • it must return a string — Python won't take a number or None;
  • __str__ with one underscore on each side won't work: you need two.

The check gives the list of heroes heroes — pairs of "name and HP". Print each one with print(hero).

Hint

__str__ must return a string, not print it.

Build it from self.name and self.hp — with concatenation or an f-string. A number doesn't go into a string by itself: str(self.hp).