liveBook · Manning

__str__

As explained in The Quick Python Book, Fourth Edition

__str__ is Python's special method for producing an informal string representation of an object.

__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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains automatic invocation and demonstrates formatting and recursive delegation, without covering lower-level implementation details.
Examples
Demonstrates RGB Color formatting, printed Circle descriptions, and recursive HTML document rendering.
What it assumes
Assumes familiarity with Python classes, methods, instances, and object-oriented programming while introducing special-method behavior.
What you can do after
Apply it via print() and str() to produce informative representations of custom class instances.
How it connects
Connects __str__ with special methods, classes, objects, print(), str(), and nested object composition.

Also explained in

Compare how 3 books explain __str__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.