What is the difference between __str__ and __repr__?

When working with Python, you might have come across the __str__ and __repr__ methods. These methods are known as "magic methods" or "special methods" in Python. They allow you to define how objects of a class should be represented as strings.

Understanding __str__

The __str__ method is used to define a string representation of an object. It is called when the str() function is invoked on an instance of a class. The main purpose of __str__ is to provide a human-readable representation of the object's state or value.

Let's consider an example to understand this better. Suppose we have a class called Person that represents a person's information:

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

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

person = Person("John", 25)
print(person)

Output:

Person(name=John, age=25)

In the above example, we have defined the __str__ method within the Person class. When we print the person object, the __str__ method is automatically called and it returns a string representation of the object with the values of its attributes.

Understanding __repr__

The __repr__ method, on the other hand, is used to define an unambiguous string representation of an object. It is called when the repr() function is invoked on an instance of a class. The main purpose of __repr__ is to provide a technical representation of the object's state or value that can be used to recreate the object.

Let's consider the same example of the Person class:

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

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

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

person = Person("John", 25)
print(repr(person))

Output:

Person(name='John', age=25)

In the above example, we have added the __repr__ method to the Person class. When we call repr(person), the __repr__ method is automatically called and it returns a string representation of the object with the values of its attributes enclosed in single quotes.

The !r format specifier is used to ensure that the values of the attributes are represented as literal strings in the __repr__ method.

Summary

In summary, the __str__ and __repr__ methods in Python serve different purposes:

  • __str__ is used to provide a human-readable representation of an object's state or value. It is called when the str() function is invoked.
  • __repr__ is used to provide a technical representation of an object's state or value that can be used to recreate the object. It is called when the repr() function is invoked.