liveBook · Manning

__repr__

As explained in Python Workout, Second Edition

__repr__ is Python's special method for producing an object's developer-oriented string representation, conventionally one that is unambiguous and potentially valid Python syntax.

Define __repr__ when an object needs a developer-oriented printed representation. Conventionally, it returns unambiguous text that may be valid Python syntax; print(obj) uses it when __str__ is absent. section 10.10

Work through the representation strategy:

  • Represent contained values by collecting their printed representations, then combine them with str.join. section 10.10
  • Use a generator expression to format each contained object lazily; a cage can place each animal on a separate indented line. section 10.30
  • Add __str__ only when developer and end-user output should differ; otherwise, __repr__ can serve both uses. section 10.10

Cage report

Create Cage(1), add wolf and sheep, and make print(c1) show the cage ID followed by each animal's representation. Extend the exercise by making subclass representations include an animal sound. section 10.29 section 10.28

Figure 10.8 A Cage instance containing one wolf and one sheep
figure

Inspect a cage instance containing one wolf and one sheep. section 10.30

How Python Workout, Second Edition covers it

How deep it goes
Explains representation roles, generator-based formatting, and nested reports, but stops short of implementation internals.
Examples
Uses bowls of scoops, cages of animals, and inherited animal representations as concrete exercises.
What it assumes
Assumes familiarity with classes, objects, inheritance, iterables, and generator expressions.
What you can do after
Apply it via Python special methods to produce useful representations for objects and containers.
How it connects
Connects __repr__ with __str__, str.join, generator expressions, object composition, and inheritance.

Also explained in

Compare how 3 books explain __repr__ →

Related concepts

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