Wednesday, June 18, 2025

What is the difference between __repr__ and __str__?

All Questions From This Chapter

__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:

python
class Book: def __init__(self, title): self.title = title def __repr__(self): return f"Book('{self.title}')"

__str__: User-Friendly Representation

  • Goal: Provide a readable or nicely formatted string for end users.

  • Used by:

    • str(obj)

    • print(obj)

Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book title: {self.title}"

💡 If Only __repr__ is Defined?

If you only define __repr__, str(obj) and print(obj) will fall back to using __repr__.


🧠 Summary:

MethodPurposeUsed ByReturn Style
__repr__Developer/debug outputrepr(), consolePrecise, evaluatable
__str__User-facing outputstr(), print()Readable, informal

Best practice: Always define __repr__. Define __str__ if you want user-friendly output.

Tags: Python,Interview Preparation,Technology,

No comments:

Post a Comment