Understanding __repr__ vs __str__ in Python – What’s the Difference?



πŸ” The Difference Between __repr__ and __str__

MethodPurposeUsed by
__repr__Developer-focused, unambiguousrepr(obj), Python shell, logs, debug
__str__User-facing, human-readableprint(obj), str(obj)

πŸ§ͺ Example

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

    def __repr__(self):
        return f"Product(id={self.id}, name='{self.name}')"

    def __str__(self):
        return self.name

Usage:

p = Product(1, "Laptop")

print(p)        # Output: Laptop        ← __str__ is used
repr(p)         # Output: Product(id=1, name='Laptop') ← __repr__ is used

In the Python shell:


πŸ‘¨β€πŸ’» Best Practices

ScenarioRecommended Method(s)
You want debug-friendly outputβœ… Implement __repr__
You want clean display for usersβœ… Add __str__
You only need one universal outputβœ… Use __repr__ and alias it: __str__ = __repr__

βœ… Quick Tip

__str__ = __repr__

πŸ”š Conclusion


✍️ This article was written with the help of AI (ChatGPT) to clarify and polish the explanation. The content has been reviewed for accuracy and tailored to developers transitioning to Python.

Leave a Reply

Your email address will not be published. Required fields are marked *