Python __str__ Method: Print Objects Nicely
What Happens When You Print an Object?
Print an object of your own class, and Python doesn't know what to show. It falls back to a default text: the class name and the object's memory address, the place where the object is stored in the computer's memory.
Think of it like a parcel with no label. The post office can tell you "a parcel, on shelf 7f3a", but not what's inside or who it's for.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rocky = Dog("Rocky", 3)
print(rocky) # <__main__.Dog object at 0x7f8b2c3d4e50>
This example isn't live, because the address is different every time it runs. The comment shows one run's output.
Reading the default text
| Part | Means |
|---|---|
__main__.Dog | the class, from the file you're running |
object | it's an object of that class |
at 0x7f8b2c3d4e50 | its memory address, written in hexadecimal (counting in 16s) |
- The address changes on every run and every computer. It tells you nothing about Rocky.
- The attributes aren't shown. Python can't guess which ones matter, or how to lay them out.
- The default text isn't an error. The program keeps running.
The quick fix you already know
You can print the attributes yourself:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rocky = Dog("Rocky", 3)
print(f"{rocky.name}, {rocky.age} years old")Rocky, 3 years old
This works, but you'd have to repeat that f-string everywhere you print a dog. In the next lesson, you'll teach the class to describe itself, once.
Printing an object with no
__str__shows its class and memory address, which is rarely what you want.