logo

Class-Based Decorators

Decorators can be classes instead of functions. This is useful when you need to maintain state.

class Counter:
    def __init__(self, func):
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call #{self.count}")
        return self.func(*args, **kwargs)

Use it like any decorator:

@Counter
def say_hello():
    print("Hello!")

say_hello()  # Call #1, Hello!
say_hello()  # Call #2, Hello!

The __init__ method receives the function (like a regular decorator). The __call__ method makes the instance callable, acting as the wrapper.

Class decorators can store data across calls, which is harder with closures.

I cover class-based decorators in my Python Decorators course.