Learn Python Coding
39.3K subscribers
653 photos
34 videos
24 files
421 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
# How to Implement a Decorator with Parameters Using a Class in Python

You can create a parameterized decorator in Python by using a class that implements the __call__ method. The class acts as the decorator factory, where the __init__ method stores the parameters, call__call__ method applies the decorator logic to the target function.

## Example Implementation

class my_decorator:
def __init__(self, param):
self.param = param

def __call__(self, func):
def wrapper(*args, **kwargs):
print(f"Decorator parameter: {self.param}")
return func(*args, **kwargs)
return wrapper

@my_decorator("Hello")
def say_hello(name):
print(f"Hello, {name}!")

say_hello("World")

## Explanation

1. Class Definition: Define a class that will serve as the decoratorinit.
2. **__init__**: Store the parameters passed to the decoracall.
3. **__call__**: Make the instance callable. This method receives the function being decorated and returns the wrappWrapperrapper**: The inner function executes the actual decorator logic before or after calling the original function.
2