CKTIS / Python
object.__str__
The string conversion method supplies a readable display form of an object.
Version: Python 3.14; repository image, production runtime not attested
Syntax
text = str(obj)The string conversion method supplies a readable display form of an object.
object.__str__
str and print use it and its result must be str. The default object implementation falls back to the diagnostic representation. A list displays its elements with repr.
The distance itself prints 3 m, while the list prints [Distance(3)].
class Invalid:
def __str__(self): return 3
try: str(Invalid())
except TypeError: pass
else: raise AssertionError
class R:
def __repr__(self): return 'R()'
assert str(R())=='R()'
Examples
class Distance:
def __init__(self, meters): self.meters=meters
def __str__(self): return f"{self.meters} m"
def __repr__(self): return f"Distance({self.meters})"
d=Distance(3)
print(d)
print([d])
Result
3 m [Distance(3)]
The distance itself prints 3 m, while the list prints [Distance(3)].