liveBook · Manning

__repr__

As explained in Python Workout: 50 ten-minute exercises

A Python special method that returns an object's developer-oriented string representation, conventionally one that could represent the object in valid Python syntax.

When printing an object should reveal useful state, define __repr__ to return a developer-oriented string, conventionally valid Python syntax. Printing an object invokes this method when it is defined; __str__ can be added later when end-user output should differ. section 9.7

A shared implementation works well with inheritance. An Animal class can format species, color, and number_of_legs from self, while Wolf, Sheep, Snake, and Parrot inherit that behavior. Subclasses can pass color and a fixed leg count through super().__init__. section 9.27

Representing contained objects

A Cage can define __repr__ to include its ID and the animals it contains, so printing a cage exposes both the container and its contents. The exercise builds cages, adds animals with add_animals, and asks the representation to display them together. section 9.31

Figure 9.13 Wolf inherits from Animal. Notice which methods are defined where.

Use the class-hierarchy figure to see which representation and initialization methods belong on Animal and which belong on Wolf. section 9.27

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines the developer-facing convention and demonstrates inheritance-based implementations, while deferring distinct end-user formatting to __str__.
Examples
Uses colored animal objects, inherited representations, scoop collections, and cages containing multiple animals.
What it assumes
Assumes familiarity with classes, instances, attributes, inheritance, and method definitions.
What you can do after
Apply it via Python special methods to format custom objects and reuse representations across an inheritance hierarchy.
How it connects
Connects __repr__ to inheritance, classes, instances, object attributes, __str__, and generator expressions.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.