__repr__ and __str__
In Python, __repr__ and __str__ are both special methods used to define how an object is represented as a string, but they serve different purposes:
✅ __repr__: Developer-Friendly Representation
-
Goal: Provide an unambiguous string representation of the object.
-
Should ideally return a string that could be used to recreate the object.
-
Used by:
-
repr(obj) -
Interactive console
-
Debugging and logging
-
Example:
✅ __str__: User-Friendly Representation
-
Goal: Provide a readable or nicely formatted string for end users.
-
Used by:
-
str(obj) -
print(obj)
-
Example:
💡 If Only __repr__ is Defined?
If you only define __repr__, str(obj) and print(obj) will fall back to using __repr__.
🧠Summary:
| Method | Purpose | Used By | Return Style |
|---|---|---|---|
__repr__ | Developer/debug output | repr(), console | Precise, evaluatable |
__str__ | User-facing output | str(), print() | Readable, informal |
✅ Best practice: Always define __repr__. Define __str__ if you want user-friendly output.

No comments:
Post a Comment