Choosing between inheritance and extension – the is-a question
In the Using cmd for creating command-line applications recipe in Chapter 5, User Inputs and Outputs, and the Extending a collection – a list that does statistics recipe in Chapter 6, Basics of Classes and Objects, we looked at extending a class. In both cases, our class was a subclass of a built-in class.
The idea of extension is sometimes called the generalization-specialization relationship. It's sometimes also called the is-a relationship.
There's an important semantic issue here that we can also summarize as the wrap versus extend problem:
- Do we really mean that the subclass is an example of the superclass? This is the is-a relationship. An example in Python is the built-in
Counter
, which extends the base classdict
. - Or do we mean something else? Perhaps there's an association, sometimes called the has-a relationship. An example of this is in the Designing classes with lots of processing recipe in Chapter 6, Basics of Classes...