๐Ÿ“ Python

The __str__ Method: Beautiful Object Output

P
Author
PyLand Team
๐Ÿ“…
Published
03.04.2026
โฑ๏ธ
Reading time
2 min
๐Ÿ‘๏ธ
Views
375
๐ŸŒฟ
Level
Medium

You print an object to the console and see: <__main__.Zombie object at 0x10e8c4d90>. Useless!

The Problem

class Zombie:
    def __init__(self, name, health):
        self.name = name
        self.health = health

walker = Zombie("Walker", 50)
print(walker)
# <__main__.Zombie object at 0x10e8c4d90>  โ† a memory address

Python doesn’t know how to display your class. It shows the object’s memory address.

The Solution: __str__

__str__ is a magic method called when you use print(object) or str(object).

class Zombie:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def __str__(self):
        return f"Zombie '{self.name}' (HP: {self.health})"

walker = Zombie("Walker", 50)
print(walker)
# Zombie 'Walker' (HP: 50)

Examples

class Zombie:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def __str__(self):
        status = "๐ŸŸข" if self.health > 30 else "๐Ÿ”ด"
        return f"{status} Zombie '{self.name}' | HP: {self.health}"

walker = Zombie("Walker", 50)
runner = Zombie("Runner", 20)
print(walker)  # ๐ŸŸข Zombie 'Walker' | HP: 50
print(runner)  # ๐Ÿ”ด Zombie 'Runner' | HP: 20
class Weapon:
    def __init__(self, name, damage, ammo):
        self.name = name
        self.damage = damage
        self.ammo = ammo

    def __str__(self):
        return f"๐Ÿ”ซ {self.name} (Damage: {self.damage}, Ammo: {self.ammo})"

pistol = Weapon("Pistol", 20, 12)
print(pistol)  # ๐Ÿ”ซ Pistol (Damage: 20, Ammo: 12)

How __str__ Works

walker = Zombie("Walker", 50)

print(walker)             # Zombie 'Walker' (HP: 50)  โ† print()
str(walker)               # Zombie 'Walker' (HP: 50)  โ† str()
f"Appeared: {walker}!"   # Appeared: Zombie 'Walker' (HP: 50)!  โ† f-strings

zombies = [Zombie("Walker", 50), Zombie("Runner", 30)]
for z in zombies:
    print(z)  # calls __str__ for each one

Rules

__str__ must return a string โ€” always return, never print.

def __str__(self):
    return f"Zombie '{self.name}'"  # โœ… returns a string

__repr__ โ€” for Debugging

class Zombie:
    def __str__(self):
        return f"Zombie '{self.name}'"              # for the user

    def __repr__(self):
        return f"Zombie(name='{self.name}', health={self.health})"  # for debugging

walker = Zombie("Walker", 50)
print(walker)        # Zombie 'Walker'
print(repr(walker))  # Zombie(name='Walker', health=50)
  • __str__ โ€” human-readable for the user
  • __repr__ โ€” precise for the developer (can be copied and executed)

Other Magic Methods

class Horde:
    def __init__(self):
        self.zombies = []

    def add(self, zombie):
        self.zombies.append(zombie)

    def __len__(self):
        return len(self.zombies)  # len(horde) โ†’ zombie count

class Zombie:
    def __eq__(self, other):
        return self.name == other.name and self.health == other.health  # z1 == z2
Method Called by Purpose
__init__ Zombie() Object creation
__str__ print(obj), str(obj), f-strings String for the user
__repr__ repr(obj) String for debugging
__len__ len(obj) Object length
__eq__ obj1 == obj2 Equality comparison
__add__ obj1 + obj2 Addition

Common Mistakes

Mistake 1: print instead of return

def __str__(self):
    print(f"Zombie '{self.name}'")  # โŒ print instead of return โ€” returns None

def __str__(self):
    return f"Zombie '{self.name}'"  # โœ…

Mistake 2: Returning a non-string

def __str__(self):
    return self.health  # โŒ TypeError: __str__ returned non-string

def __str__(self):
    return f"HP: {self.health}"  # โœ…

Summary

__str__ is a magic method for beautiful object output. It’s called automatically by print(), str(), and inside f-strings. It must always return a string via return.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 44
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 50
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 89
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Python from Scratch: Build 7 Practical Projects Open course curriculum