In Python, string representation refers to how objects are represented as strings. This feature is essential for debugging and logging purposes.
Python offers two primary special methods for defining string representations:
.__str__()
is intended to provide a nice or user-friendly string representation of an object.__repr__()
aims to provide a more precise and developer-friendly string representation that can often be used to recreate the object.When you print an object or use the built-in str()
function, Python internally calls the .__str__()
method. If .__str__()
isn’t defined, then Python falls back to .__repr__()
. Conversely, if you use the built-in repr()
function or access the object in a REPL, Python calls .__repr__()
.
Here’s an example that illustrates both string representations:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __str__(self):
return f"{self.make} {self.model}"
def __repr__(self):
cls = type(self).__name__
return f"{cls}(make='{self.make}', model='{self.model}')"
# Usage
corolla = Car("Toyota", "Corolla")
print(str(corolla)) # Output: Toyota Corolla
print(repr(corolla)) # Output: Car(make='Toyota', model='Corolla')
Copied!
In this example, .__str__()
provides a user-friendly description of the concrete Car
object, while .__repr__()
gives a developer-friendly representation suitable for debugging.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4