Extending a collection – a list that does statistics
In the Designing classes with lots of processing recipe we looked at a way to distinguish between a complex algorithm and a collection. We showed how to encapsulate the algorithm and the data into separate classes.
The alternative design strategy is to extend the collection to incorporate a useful algorithm.
How can we extend Python's built-in collections?
Getting ready
We'll create a sophisticated list that can compute the sums and averages of the items in the list. This will require that our application only puts numbers in the list; otherwise, there will be ValueError
exceptions.
How to do it...
- Pick a name for the list that also does simple statistics. Define the class as an extension to the built-in
list
class:
class StatsList(list):
This shows the syntax for defining an extension to a built-in class. If we provide a body that consists only of the pass
statement, then the new StatsList
class can be used anywhere the list
class...