Extending a built-in 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? How can we add features to the built-in list?
Getting ready
We'll create a sophisticated list class where each instance can compute the sums and averages of the items in the list. This will require an application to only put numbers in the list; otherwise, there will be ValueError
exceptions.
We're going to show methods that explicitly use generator expressions as places where additional processing can be included. Rather than use sum(self)
, we're going to emphasize sum(v for v in self)
because there are two common future extensions...