If you’re coming from a Java background like me, you’re probably used to overriding toString()
to define how your objects are printed. In Python, things are a bit different. Python gives us two special methods for object representation: __repr__
and __str__
.
At first glance, they seem interchangeableβbut they actually serve different purposes. Here’s a clear breakdown of what each one does, and when to use them.
π The Difference Between __repr__
and __str__
Method | Purpose | Used by |
---|---|---|
__repr__ | Developer-focused, unambiguous | repr(obj) , Python shell, logs, debug |
__str__ | User-facing, human-readable | print(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:
Typing just p will show the __repr__
output by default.
π¨βπ» Best Practices
Scenario | Recommended 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
If you want both methods to return the same result (like Java’s toString()
):
__str__ = __repr__
This tells Python to use the same logic for both representations.
π Conclusion
Python separates technical (developer/debug) and user-facing representations of objects by design. While it might seem redundant at first, this distinction gives you precise control over how your objects are presented in different contexts.
If you’re building data models, DTOs, or anything you plan to log or print, having a clean __repr__
(and optionally a __str__
) is highly recommended.
βοΈ 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.