How do you write a decorator as a CLASS instead of a function, implementing __call__?
Short answer
A class-based decorator stores the wrapped function (typically in __init__) and implements __call__ to actually invoke it — useful when the decorator needs to maintain PERSISTENT state (like a call counter) across multiple calls, more naturally expressed as instance attributes…
Advertisement
AModel answer
A class-based decorator stores the wrapped function (typically in __init__) and implements __call__ to actually invoke it — useful when the decorator needs to maintain PERSISTENT state (like a call counter) across multiple calls, more naturally expressed as instance attributes than closure variables.
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
print(f"Call #{self.calls} to {self.func.__name__}")
return self.func(*args, **kwargs)
@CountCalls
def greet():
print("Hello!")Real-world example
Building a decorator that needs to track state across every call, like counting invocations or caching results with explicit management.
Likely follow-ups
- Why does functools.update_wrapper() need to be used here instead of the simpler @functools.wraps decorator syntax?
Related topics