Class Decorator

Use a class as a decorator to wrap functions with additional behavior.

PythonIntermediate
Python
# Program to demonstrate a simple class decorator

class CallLogger:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print(f"Calling {self.func.__name__}")
        return self.func(*args, **kwargs)


@CallLogger
def greet(name):
    print("Hello,", name)


greet("Alice")

Output

Calling greet
Hello, Alice

Implementing call in a class allows its instances to behave like functions and be used as decorators.