Junior — Middle
How to implement a decorator function that accepts parameters?
sobes.tech AI
Answer from AI
A decorator function with parameters is implemented as a function that returns the decorator itself. That is, it involves three levels of nesting:
- The outer function accepts the decorator parameters.
- The inner function is the decorator itself, which accepts the function to be wrapped.
- The wrapper function, which replaces the original function.
Example:
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def say_hello():
print("Hello")
say_hello()
In this example, repeat is a function that takes the parameter times. It returns decorator, which takes the function func and returns wrapper, which calls func the specified number of times.