Concept Explanation
When you try to print a complex Python object, like a custom Person object, Python usually gives you some ugly nonsense like: <__main__.Person object at 0x000001>. This isn't very helpful for a human developer.
The __str__() method is a special "Dunder" (Double Under-score) method that tells Python exactly how you want your object to be represented as a string. Whenever you call print(my_object) or str(my_object), Python checks if the class has a __str__ method and uses its return value.
Syntax or Core Structure
Defining the String Representation
The method must always return a string.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
# Custom string representation
def __str__(self):
return f"'{self.title}' by {self.author}"
my_book = Book("Atomic Habits", "James Clear")
print(my_book) # Result: 'Atomic Habits' by James Clear
Code Example #1 (Basic)
Adding basic descriptive info to a character object.
class Hero:
def __init__(self, name, level):
self.name = name
self.level = level
def __str__(self):
return f"Hero Profile: {self.name} (Lvl {self.level})"
player = Hero("Xander", 15)
print(player)
Code Example #2 (Intermediate)
Using string formatting to create clean multi-line reports from an object.
class Invoice:
def __init__(self, customer, amount):
self.customer = customer
self.total = amount
self.paid = False
def __str__(self):
status = "PAID" if self.paid else "PENDING"
return (f"--- INVOICE ---
"
f"Client: {self.customer}
"
f"Total: ${self.total:,.2f}
"
f"Status: {status}
"
f"---------------")
inv = Invoice("Hyperion Corp", 5000)
print(inv)
Real World Example
Imagine a library system where you need to display search results. Instead of custom printing logic everywhere, the objects know how to describe themselves.
# 📚 Library System Simulation
class Member:
def __init__(self, name, id):
self.name = name
self.id = id
def __str__(self):
return f"[ID:{self.id}] Name: {self.name}"
users = [Member("Alice", 101), Member("Bob", 102)]
for u in users:
print(u)
Common Mistakes
- Forgetting the Return Keyword:
__str__MUST return a string. If you print inside__str__but don't return anything, Python will throw aTypeError. - Returning Non-Strings: Even if you want to return a number, you must convert it:
return str(self.id). - Overcomplicating: Keep the
__str__method relatively short and focused on the most important identity information.
Best Practices
- Make it Readable: The string should contain enough info to identify the object uniquely.
- Use f-strings: They are the most readable way to build your return string.
- Differentiate from __repr__():
__str__is for humans;__repr__is for developers (and usually looks like the code used to create the object).
Practice Exercises
- The Fruit Bowl: Create a
Fruitclass that takes anameandcolor. Define__str__to return "A [color] [name]". - The Coordinate System: Create a
Pointclass that takesxandy. Define__str__so it prints like this:(x, y). - The User Bio: Create a
Userclass withusername,role, andjoin_date. Format__str__to return a professional-looking badge.