Writing Parameterized Decorators
Deslize para mostrar o menu
When you want your decorator to behave differently depending on some input, you need to create a parameterized decorator. Unlike regular decorators, which only take the function as an argument, parameterized decorators accept their own arguments, allowing you to control their behavior dynamically. This is especially useful when you want to reuse a decorator in multiple situations with different configurations.
The Structure of a Parameterized Decorator:
- The outer function accepts the decorator arguments;
- The middle function is the actual decorator that takes the function to be decorated;
- The inner function wraps and controls the execution of the original function.
This layered approach lets you pass arguments to the decorator, which are then available when the decorated function is called.
12345678910111213141516171819202122# Outer function: accepts the decorator argument 'times' def repeat(times): # The actual decorator that takes the function to be decorated def decorator(func): # Inner function: wraps and controls the execution of 'func' def wrapper(*args, **kwargs): result = None # Call the original function 'times' times for _ in range(times): result = func(*args, **kwargs) return result # Return the wrapper to replace the original function return wrapper # Return the decorator function return decorator # Apply the repeat decorator @repeat(3) def say_hello(): print("Hello!") say_hello()
1. How does a parameterized decorator differ from a regular decorator?
2. Why might you want to pass arguments to a decorator?
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 4. Capítulo 3
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Seção 4. Capítulo 3