What is `__str__` vs `__repr__`

The `__str__` and `__repr__` methods in Python are both used to define string representations for objects, but they serve different purposes.

__str__: This method is intended to provide a "friendly" string representation of an object. It is used by the built-in `str()` function and the `print()` function. Its primary goal is to be easily readable.

__repr__: This method is used to define an "official" string representation of an object that can ideally be used to reproduce the object using the `eval()` function. It is meant for developers and should be unambiguous.

Here's an example demonstrating the difference between `__str__` and `__repr__`:

class Sample: def __init__(self, value): self.value = value def __str__(self): return f'Sample with value: {self.value}' def __repr__(self): return f'Sample({self.value})' obj = Sample(10) print(str(obj)) # Output: Sample with value: 10 print(repr(obj)) # Output: Sample(10)

__str__ __repr__ Python object representation developer string conversion programming