Conteúdo do Curso
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
Closure with Arguments
There are different ways to use arguments in closure:
- Argument for the outer function.
- Argument for the inner function.
Outer Argument
Arguments for the outer function is used to enclose the values inside the function exactly once. This works like initialization:
The example above implements a counter function. The start_count()
function takes two arguments: start
and step
, with default values of 1
. The start
value is assigned to the variable counter
. The counter
and step
are then used inside the inner()
function.
The arguments' values start
(counter
) and step
are enclosed in the inner() function as parameters for the counter.
The variables first_counter
and second_counter
contain the inner()
functions with enclosed parameters. These variables are functions that can be called without parameters.
Note
The variables
first_counter
andsecond_counter
are independent counters: as an example, we can see how each of them has its own separate value and performs certain actions.
Inner Arguments
The inner()
function is a returned function assigned to variables. The arguments that the inner()
takes are used every time the inner()
function is called via variables.
Arguments passed to the inner()
function behave like regular function arguments and are not related to the closure.
Tudo estava claro?