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 *