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.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!