The __str__() Function

The __str__() Function in Python: When you try to print a complex Python object, like a custom object, Python usually gives you some ugly nonsense like: .

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

  1. Forgetting the Return Keyword: __str__ MUST return a string. If you print inside __str__ but don't return anything, Python will throw a TypeError.
  2. Returning Non-Strings: Even if you want to return a number, you must convert it: return str(self.id).
  3. 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

  1. The Fruit Bowl: Create a Fruit class that takes a name and color. Define __str__ to return "A [color] [name]".
  2. The Coordinate System: Create a Point class that takes x and y. Define __str__ so it prints like this: (x, y).
  3. The User Bio: Create a User class with username, role, and join_date. Format __str__ to return a professional-looking badge.