Contenido del Curso
Intermediate Python Techniques
Intermediate Python Techniques
Decorators with Parameters
Decorators with parameters in Python are an advanced feature that allow you to pass additional arguments to your decorators, enhancing their flexibility. Here's a practical example to illustrate this concept:
Basic Decorator Structure
First, let's start with a basic decorator structure:
def simple_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @simple_decorator def say_hello(): print("Hello!") say_hello()
In this example, simple_decorator is a regular decorator that modifies the behavior of the say_hello function.
Decorator with Parameters
Now, let's create a decorator that accepts parameters:
def decorator_with_args(arg1, arg2): def decorator(func): def wrapper(*args, **kwargs): print(f"Decorator args: {arg1}, {arg2}") return func(*args, **kwargs) return wrapper return decorator @decorator_with_args("hello", 42) def print_numbers(a, b): print(a + b) print_numbers(10, 5)
In this example, decorator_with_args
is a decorator factory that accepts parameters (arg1, arg2) and returns the actual decorator (decorator). The wrapper function is the one that modifies the behavior of the decorated function (print_numbers).
Explanation
decorator_with_args
is called with its arguments("hello", 42)
;- It returns the
decorator
function; decorator
takes a functionprint_numbers
and returns thewrapper
function;wrapper
has access to both the arguments ofdecorator_with_args
and the arguments ofprint_numbers
.
This structure allows for greater flexibility and reusability of decorators, as you can pass custom arguments to modify their behavior.
¡Gracias por tus comentarios!