SyntaxStudy
Sign Up
Python Class-Based Decorators
Python Intermediate 4 min read

Class-Based Decorators

Class-Based Decorators

A class can act as a decorator by implementing __call__. This is useful when you need to maintain state across calls.

Example
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
Pro Tip

Class decorators are great when the decorator needs to store state.