accumulators

Leif K-Brooks eurleif at ecritters.biz
Sun Jun 13 02:18:23 CEST 2004


Paul Rubin wrote:
>   class accum:
>     def __init__(self, n):
>        self.s = n
>     def __call__(self, i):
>        self.s += i
>        return self.s

Just for fun, a full-blown class with documentation and the like:

class Accumulator(object):
     """This class implements a simple accumulator. Instate it with a
     starting value, or it will default to 0. It can be called with
     another value, which will be accumulated. The current value will
     also be returned.

     Example:

     >>> a = Accumulator(1)
     >>> a(2)
     3
     >>> a(1)
     4
     >>> a(3)
     7
     """

     __slots__ = '_value'

     def __init__(self, value=0):
         self._value = value

     def __call__(self, value):
         self._value += value
         return self._value

     def __str__(self):
         return str(self._value)

     def __repr__(self):
         return "<Accumulator object with value %s>" % self._value



More information about the Python-list mailing list