[Tutor] Counting method calls
Ricardo Aráoz
ricaraoz at gmail.com
Sat Sep 22 15:25:14 CEST 2007
Kent Johnson wrote:
> Ricardo Aráoz wrote:
>> Hi, I'm trying to count method calls. Tried this but...
>>>>>> class MyList(list):
>>> ... def __init__(self):
>>> ... self.calls = 0
... snipped .....
> I think this does what you want. Notice that it doesn't have anything
> special to do with lists, either, except instantiating a list. It can be
> turned into a general-purpose counting wrapper by passing the instance
> to be counted to the constructor:
>
> class CallCounter(object):
> def __init__(self, delegate):
> self._delegate = delegate
> self.calls = 0
> def __getattr__(self, name):
> value = getattr(self._delegate, name)
> if callable(value):
> self.calls += 1
> return value
>
> a = CallCounter(list())
>
> etc.
>
> Kent
>
Thanks Kent!
More information about the Tutor
mailing list