In Python, both __str__
and __repr__
are special methods used to provide string representations of objects. The __str__
method is used for creating user-friendly, human-readable string representations. It is typically used for displaying the object to end-users. On the other hand, the __repr__
method is used to provide a detailed, unambiguous representation of the object. It is mainly used for debugging purposes and should ideally be a valid Python expression that can recreate the object. If __str__
is not defined, Python falls back to using __repr__
.
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}', age={self.age})"
person = Person("Alice", 25)
# Using str()
print(str(person))
# Using repr()
print(repr(person))
Person(name=Alice, age=25)
Person(name='Alice', age=25)
In this example, we define a Person
class with two attributes: name
and age
. The class has two special methods: __str__
and __repr__
.
The __str__
method is called by the built-in str()
function and provides a human-readable string representation of the object. It is intended for end-users to understand and display the object. In this example, __str__
returns a formatted string that includes the name and age of the person.
The __repr__
method is called by the built-in repr()
function and provides an unambiguous string representation of the object. It is mainly used for debugging purposes and should ideally be a valid Python expression that can recreate the object. In this example, __repr__
returns a string representation that includes the name and age of the person, enclosed in quotes.
When we create an instance of the Person
class and print it using str(person)
, it calls the __str__
method and returns a user-friendly string representation, "Person(name=Alice, age=25)"
. The __str__
method is used to provide a more readable representation for the end-user.
On the other hand, when we print the object using repr(person)
, it calls the __repr__
method and returns an unambiguous string representation, "Person(name='Alice', age=25)"
. The __repr__
method provides a detailed representation that includes the actual Python expression to recreate the object.
By implementing both __str__
and __repr__
methods in a class, you can control how the object is displayed in different contexts, providing more meaningful output for users and more detailed information for debugging purposes.