__str__ is a special method that supplies an informal, user-readable string representation of an object. Python invokes it automatically when an instance is used where such a representation is required, especially with print() or str(). Define it to make instances easy to inspect and understand. section 17.5 section 3.6
Listing 17.1 File color_module.py
class Color:
def __init__(self, red, green, blue):
self._red = red
self._green = green
self._blue = blue
def __str__(self):
return f"Color: R={self._red:d},G={self._green:d},B={self._blue:d}"
A Color class formats its three component values into a readable string without requiring client code to call __str__() directly. section 17.5
Printing a formatted object
With Color(15, 35, 3), calling print(c) produces `Color: R=15, G=35, B=3`. The print call triggers the class's __str__ method implicitly. section 17.5
The method can also assemble a larger representation by delegating to a contained object's __str__ method. An HTML document can therefore render its body and paragraph recursively when str() is called on the outer html element. section 15.14
para = p(text="this is some body text") doc_body = body(text="This is the body", subelement=para) doc = html(subelement=doc_body) print(doc) <html> <body> This is the body <p> this is some body text </p> </body> </html>
This runnable example shows nested HTML objects producing a complete document through chained __str__ calls. section 15.14


