Class-Based Decorators
A class can act as a decorator by implementing __call__. This is useful when you need to maintain state across calls.
A class can act as a decorator by implementing __call__. This is useful when you need to maintain state across calls.
class CallCounter:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@CallCounter
def greet():
return "Hello"
greet(); greet()
print(greet.count) # 2
Class decorators are great when the decorator needs to store state.