Sobes.tech
Junior — Middle

What is the purpose of __str__ and __repr__ methods in Python and how do they differ?

sobes.tech AI

Answer from AI

The __repr__ and __str__ methods in Python serve to provide string representations of an object, but they have different purposes:

  • __repr__ is meant to provide an official string representation of the object, which should be as informative as possible and, if possible, such that it can be used to recreate the object (e.g., via eval). If not, it should return a string with useful information.

  • __str__ is meant to provide a user-friendly, "pretty" string representation of the object for end-users.

If __str__ is not defined, Python defaults to using __repr__.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(1, 2)
print(repr(p))  # Outputs: Point(1, 2)
print(str(p))   # Outputs: (1, 2)

Thus, __repr__ is for developers and debugging, __str__ is for users.