Course contentsShow
← Python
Lesson 446 of 1,0607. Object-Oriented ProgrammingFree lesson

Defining Object String Representations

Implement the __str__ and __repr__ methods to provide meaningful and debugging-friendly string outputs for your custom class instances.

In this lesson, you will learn how to make your custom objects readable and debug-friendly by implementing the special __str__ and __repr__ methods.

When you create a custom class, printing an instance usually results in a cryptic message like <__main__.Book object at 0x7f...>. This is the default Python representation, but it doesn’t tell you anything about your object's data. To fix this, we use two special "dunder" (double underscore) methods.

The Purpose of __str__ and __repr__

  • __str__ is intended to be user-friendly. It should return a clean, readable string that describes the object, intended for end-users. It is triggered when you use print() or str().
  • __repr__ is intended to be developer-friendly. Its goal is to be unambiguous and, ideally, represent the exact code needed to recreate the object. It is used for debugging and is triggered by the repr() function or when viewing objects in an interactive console.

Implementation Example

Here is how you would implement these in a simple Product class:

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        # A human-readable summary
        return f"{self.name} costs ${self.price:.2f}"

    def __repr__(self):
        # A developer-readable string to recreate the object
        return f"Product(name='{self.name}', price={self.price})"

item = Product("Laptop", 999.99)

print(str(item))   # Output: Laptop costs $999.99
print(repr(item))  # Output: Product(name='Laptop', price=999.99)

In this code, __str__ provides a tidy sentence, while __repr__ shows the constructor arguments, making it easy for you to spot exactly what the object contains while debugging.

A common best practice is to always define __repr__ at a minimum. If you define __repr__ but skip __str__, Python will use your __repr__ output whenever it needs a string version of the object. This ensures your objects are never represented by a cryptic memory address again!

Key Takeaway: Implement __str__ to provide a human-readable summary for your users, and implement __repr__ to provide an unambiguous, developer-focused description for debugging.