Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Decorators with Parameters | Decorators
course content

Зміст курсу

Intermediate Python: Arguments, Scopes and Decorators

Decorators with ParametersDecorators 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 function print_numbers and returns the wrapper function;
  • wrapper has access to both the arguments of decorator_with_args and the arguments of print_numbers.

This structure allows for greater flexibility and reusability of decorators, as you can pass custom arguments to modify their behavior.

Все було зрозуміло?

Секція 5. Розділ 4
course content

Зміст курсу

Intermediate Python: Arguments, Scopes and Decorators

Decorators with ParametersDecorators 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 function print_numbers and returns the wrapper function;
  • wrapper has access to both the arguments of decorator_with_args and the arguments of print_numbers.

This structure allows for greater flexibility and reusability of decorators, as you can pass custom arguments to modify their behavior.

Все було зрозуміло?

Секція 5. Розділ 4
some-alt