How to do it...

  1. Define the class with a descriptive name:

        class LazyCounterStatistics: 
  1. Write the initialization method to include the object to which this object will be connected:
        
def __init__(self, raw_counter:Counter): 
            self.raw_counter = raw_counter
 

We've defined a method function that takes a Counter object as an argument value. This counter object is saved as part of the Counter_Statistics instance.

  1. Define some useful helper methods. Each of these is decorated with @property to make it behave like a simple attribute:

        @property 
        def sum(self): 
            return sum(f*v for v, f in self.raw_counter.items()) 
        @property 
        def count(self): 
            return sum(f for v, f in self.raw_counter.items())
  1. Define the required methods for the various values. ...

Get Modern Python Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.