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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.