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)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?