liveBook · Manning

Class hierarchy

As explained in Python Workout, Second Edition

A class hierarchy is an organization of classes into parent-child relationships that represent shared and specialized behavior.

A class hierarchy organizes related classes into parent-child relationships. Child classes inherit functionality from parents, reducing repeated code while preserving distinctions among specialized data types. section 10.2

Practice the design by extending an animal hierarchy:

  • Place Animal above Wolf, Sheep, Snake, and Parrot, then compare direct inheritance with intermediate ZeroLeggedAnimal, TwoLeggedAnimal, and FourLeggedAnimal classes. section 10.28
  • Decide whether shared initialization belongs in Animal, whether subclasses need their own __init__, and whether number_of_legs should be a class attribute. section 10.28
  • Use inheritance to reuse repr behavior while producing strings that combine an animal’s sound with its standard description. section 10.28

Treat the public interface as the stable surface: callers use methods and behavior without needing to manage the class’s internal implementation. section 10.2

How Python Workout, Second Edition covers it

How deep it goes
Explains inheritance through animal-class design questions, but stops short of a complete implementation.
Examples
Uses Animal, Wolf, Sheep, Snake, Parrot, and leg-count subclasses to explore hierarchy design and repr behavior.
What it assumes
Assumes familiarity with Python classes and object-oriented concepts while emphasizing interfaces over hidden implementation details.
What you can do after
Build it from scratch by designing parent and child classes, choosing shared initialization, and reusing inherited methods.
How it connects
Connects inheritance with object-oriented programming, abstraction, interfaces, class attributes, and method reuse.

Also explained in

Compare how 4 books explain class hierarchy →

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.