Class Decorator in Python

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

IntermediateObject-Oriented ProgramsExample 21 of 25
class-decorator.py
Run in browser
1# Program to demonstrate a simple class decorator
2
3class CallLogger:
4 def __init__(self, func):
5 self.func = func
6
7 def __call__(self, *args, **kwargs):
8 print(f"Calling {self.func.__name__}")
9 return self.func(*args, **kwargs)
10
11@CallLogger
12def greet(name):
13 print("Hello,", name)
14
15greet("Alice")

Output

Calling greet
Hello, Alice

What's going on

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