The Difference between __str__ and __repr__ in Python

09/16/2021

Contents

In this article, you will learn about the difference between __str__ and __repr__ in Python.

The difference between __str__ and __repr__

In Python, both __str__ and __repr__ are special methods that allow you to define how an object should be represented as a string. However, they have different purposes and are used in different contexts.

__repr__ is short for “representation” and is intended to provide a complete, unambiguous representation of the object, including its type and all its attributes. The __repr__ method is used by the built-in repr() function and should be used to provide a string that, when passed to eval(), would recreate the original object.

Here’s an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

p = Person('Alice', 25)
print(repr(p))  # Output: Person('Alice', 25)
 

__str__, on the other hand, is short for “string” and is intended to provide a human-readable representation of the object. The __str__ method is used by the built-in str() function and should be used to provide a string that represents the object in a way that is easy for humans to read and understand.

Here’s an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

p = Person('Alice', 25)
print(str(p))  # Output: Alice is 25 years old

Note that if you don’t define a __str__ method for your class, Python will use the __repr__ method as a fallback. However, the opposite is not true – if you don’t define a __repr__ method, Python will use a default implementation that does not include any of the object’s attributes.

In summary, __repr__ should be used to provide a complete, unambiguous representation of the object, while __str__ should be used to provide a human-readable representation of the object.