Contenido del Curso
Intermediate Python: Arguments, Scopes and Decorators
2. Arguments in Function
3. Function as an Argument
Intermediate Python: Arguments, Scopes and Decorators
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:
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:
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.
¿Todo estuvo claro?
Contenido del Curso
Intermediate Python: Arguments, Scopes and Decorators
2. Arguments in Function
3. Function as an Argument
Intermediate Python: Arguments, Scopes and Decorators
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:
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:
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.
¿Todo estuvo claro?