Class-based decorator uses a class to implement the decorator pattern. Useful for maintaining state.
1import functools23class CountCalls:4 def __init__(self, func):5 functools.update_wrapper(self, func)6 self.func = func7 self.call_count = 089 def __call__(self, *args, **kwargs):10 self.call_count += 111 print(f"Call #{self.call_count} to {self.func.__name__}")12 return self.func(*args, **kwargs)1314 def reset(self):15 self.call_count = 01617@CountCalls18def say_hello(name):19 return f"Hello, {name}!"2021say_hello("Alice") # Call #1 to say_hello22say_hello("Bob") # Call #2 to say_hello23print(say_hello.call_count) # 224say_hello.reset() # Reset counter
Class-based vs function-based:
@decorator syntax.