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 browser1# Program to demonstrate a simple class decorator23class CallLogger:4 def __init__(self, func):5 self.func = func67 def __call__(self, *args, **kwargs):8 print(f"Calling {self.func.__name__}")9 return self.func(*args, **kwargs)1011@CallLogger12def greet(name):13 print("Hello,", name)1415greet("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.