Choosing between inheritance and composition – the "is-a" question
In the Using cmd for creating command-line applications recipe in Chapter 6, User Inputs and Outputs, and the Extending a collection – a list that does statistics recipe in Chapter 7, Basics of Classes and Objects, we looked at extending a class. In both cases, the class implemented in the recipe was a subclass of one of Python's built-in classes. In Chapter 7, Basics of Classes and Objects, we defined the DiceCLI
class to extend the cmd.Cmd
class via inheritance. In We also defined a StatsList
class to extend the built-in list
class.
The idea of extension via inheritance is sometimes called the generalization-specialization relationship. It's sometimes also called an is-a relationship.
There's an important semantic issue here: it's sometimes referred to as the wrap versus extend problem. There are two common choices:
- Do we mean that instances of the subclass...