Python’s str and repr: Differences for Clear Object Representations

python @ Freshers.in

In Python, the __str__ and __repr__ methods play a crucial role in determining how an object is represented when converted to a string. Understanding the differences between these methods is essential for creating informative and readable code. In this article, we’ll delve into the distinctions between __str__ and __repr__, providing real-world examples to illustrate their usage. Understanding the distinction between __str__ and __repr__ empowers Python developers to create more informative and readable code.

The Purpose of str and repr

Both __str__ and __repr__ are methods used to define the string representation of an object. However, they serve different purposes:

  • __str__: Intended for creating the informal, user-friendly representation of the object. Used by the str() function and the print() function when displaying the object.
  • __repr__: Designed for creating a formal, unambiguous representation of the object. Used by the repr() function and displayed when the __str__ method is not defined.

Real-World Example: Custom Class Representation

Consider a Point class representing a point in 2D space. Let’s implement __str__ and __repr__ methods for better object representation:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return f"Point(x={self.x}, y={self.y})"
    def __repr__(self):
        return f"Point({self.x}, {self.y})"
# Example usage
point = Point(3, 4)
print(str(point))   # Output: Point(x=3, y=4)
print(repr(point))  # Output: Point(3, 4)

Use Cases for str and repr

  • __str__ for End-User Output: When you want a readable and user-friendly representation of the object.
  • __repr__ for Debugging and Developer Output: When you need a detailed and unambiguous representation for debugging and development purposes.

Default Implementations

If __str__ is not defined, Python will use the result of __repr__ as a fallback when calling str() on an object.

class Example:
    def __repr__(self):
        return "Default __repr__"
obj = Example()
print(str(obj))  # Output: Default __repr__

Refer more on python here :

Author: Freshers