liveBook · Manning

__str__

As explained in Python Workout: 50 ten-minute exercises

A Python special method that returns an object's user-oriented string representation.

When an object needs a readable description, __str__ supplies the form intended for end users. It contrasts with __repr__, which is aimed at developers and should, in theory, produce legitimate Python syntax. section 9.7

Use the surrounding string tools to make representations useful:

  • Use str(value) to convert integers and other values into strings. section 1.22 section 1.3
  • Convert every item before passing a sequence to str.join, because join expects strings. section 7.2
  • Define __repr__, __str__, or both; a pragmatic style often defines __repr__ and omits __str__. section 9.7

A readable Bowl representation

A Bowl can store Scoop instances in a list, preserving each scoop's flavor rather than storing only flavor strings. Printing the Bowl demonstrates object representation; __repr__ can join the extracted flavors, while __str__ is available for an explicitly user-oriented form. section 9.7

numbers = range(15)

print(','.join(str(number)
               for number in numbers))

This listing shows the practical pattern of converting each number with str before joining the results. section 7.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines the audience distinction and shows a Bowl example, but defers deeper object-model mechanics.
Examples
Uses Bowl and Scoop objects, numeric conversion with str(5), and joining converted ranges.
What it assumes
Assumes familiarity with Python objects, classes, lists, and strings while reinforcing conversion and joining.
What you can do after
Apply it via Python string conversion and object representation choices for readable output.
How it connects
Connects __str__ with __repr__, str conversion, str.join, lists, and list comprehensions.

Also explained in

Compare how 3 books explain __str__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.