What is the purpose of `__str__` and `__repr__` in Python classes?
`__str__` is used for a user-friendly string representation, while `__repr__` is for an unambiguous representation useful for debugging. Implement both for better usability.
In Python, __str__
and __repr__
are special methods used to define string representations of class instances, serving different purposes. The __str__
method is intended to provide a user-friendly string representation of an object, which is more readable and suitable for display to end users. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'{self.name}, {self.age} years old'
On the other hand, the __repr__
method is used to provide a more detailed and unambiguous string representation that is useful for debugging. It should ideally return a string that can be used to recreate the object:
def __repr__(self):
return f'Person(name={self.name!r}, age={self.age!r})'
By implementing both methods in your classes, you enhance their usability and provide clear insights into their state, making it easier for developers to interact with your objects effectively.