Readable object output
Display domain objects in logs, command-line output, or user-facing messages.
Python · Module
__str__(self) defines an object's informal, human-readable string representation. Python uses it through str(), print(), and default formatting, and the method must return a str.
Define __str__(self) on a class to control its informal, user-facing string representation. Python invokes it for str(obj), print(obj), and the default formatting operation; the method must return a str. If omitted, the inherited implementation produces the ordinary object representation.
object.__str__(self)| Name | Type | Description |
|---|---|---|
self | object | The instance whose informal string representation is being computed. |
A str object containing the object's informal or nicely printable representation.
__str__ for str(), ordinary formatting, and print().__repr__ implementation.__str__ is the user-facing counterpart to the more formal __repr__ hook.__str__ raises an error; always return a str.__repr__, the result may be concise and human-oriented rather than evaluable Python syntax.class User:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
user = User("Ada")
print(str(user))
print(f"{user}")The class supplies a concise human-readable string used by str(), print(), and default formatting.
Display domain objects in logs, command-line output, or user-facing messages.
Make f-strings and ordinary formatting show meaningful instance data.
Expose a concise representation for objects whose internal state is too verbose for normal display.
__str__ used for?__str__(self) returns an object's informal or nicely printable representation. It is used by str(obj), print(obj), and the default __format__() implementation, and it must return a str.
Follow-up: What happens if the method is absent? The built-in object implementation calls object.__repr__() instead.
__str__ differ from __repr__?The method receives only self and should return the text users should normally see for the instance. It is appropriate for a convenient, concise representation rather than a debugging-oriented representation.
Follow-up: How does it differ from __repr__? __repr__ aims at an official representation, while __str__ has no requirement to produce valid Python code.
__str__ override satisfy?The signature is object.__str__(self), and an override keeps the same one-argument instance-method shape. Returning a non-str violates the documented contract.
Follow-up: Which formatting path invokes it? The default __format__() implementation delegates to __str__() when formatting has no explicit format specification.
__repr____format__strprintformat