The class you have shown us is not a decorator -- it is simply a class. Accessing the counter is as easy as
SomeClass.counter
# current counter value
Making your class an actual decorator is not difficult -- I'll rename it to Counter
, however.
class Counter:
"""
Count the number of calls made to the wrapped function.
"""
def __init__(self, func):
self.counter = 0
self.func = func
def __call__(self, *args, **kwds):
self.counter += 1
return self.func(*args, **kwds)
@Counter
def square(n):
return n * n
and in use:
square(3)
# 9
square(7)
# 41
square(11)
# 121
square.counter
# 3
Note: This is a very simple decorator, and one side-effect is that the signature of the wrapped function is lost.
the unwrapped signature:
Help on function square in module __main__:
square(n)
the wrapped signature:
Help on instance of Counter in module __main__:
class Counter
| Count the number of calls made to the wrapped function.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
|
| __init__(self, func)