- Mastering Objectoriented Python
- Steven F. Lott
- 400字
- 2021-11-12 16:25:17
Summary, design considerations, and trade-offs
In this chapter, we looked at the essential ingredients of abstract base classes. We saw a few features of each kind of abstraction.
We also learned that one rule for good class design is to inherit as much as possible. We saw two broad patterns here. We also saw common exceptions to this rule.
Some application classes don't have behaviors that overlap with internal features of Python. From our Blackjack examples, a Card
isn't much like a number, a container, an iterator, or a context. It's just a playing card. In this case, we can generally invent a new class because there isn't any built-in features to inherit fro.
When we look at Hand
, however, we see that a hand is clearly a container. As we noted when looking at hand classes in Chapters 1, The __init__() Method, and Chapter 2, Integrating Seamlessly with Python – Basic Special Methods, the following are three fundamental design strategies:
- Wrapping an existing container
- Extending an existing container
- Inventing a wholly new kind of container
Most of the time, we'll be wrapping or extending an existing container. This fits with our rule of inheriting as much as possible.
When we extend an existing class, our application class will fit into the class hierarchy neatly. An extension to the built-in list
is already an instance of collections.abc.MutableSequence
.
When we wrap an existing class, however, we have to consider carefully what parts of the original interface we want to support and what parts we don't want to support. In our examples in the previous chapters, we only wanted to expose the pop()
method from the list object we were wrapping.
Because a wrapper class is not a complete mutable sequence implementation, there are many things it can't do. On the other hand, an extension class participates in a number of use cases that just might turn out to be useful. For example, a hand that extends list
will turn out to be iterable.
If we find that extending a class doesn't meet our requirements, we can resort to building an entirely new collection. The ABC definitions provide a great deal of guidance on what methods are required in order to create a collection that can integrate seamlessly with the rest of the Python universe. We'll look at a detailed example of inventing a collection in Chapter 6, Creating Containers and Collections.