Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Closure with Arguments | Closure
Mastering Python: Closures and Decorators
course content

Зміст курсу

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

bookClosure with Arguments

There are different ways to use arguments in closure:

  1. Argument for the outer function.
  2. 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:

12345678910111213141516171819202122232425262728293031
def start_count(start=1, step=1): counter = start def inner(): nonlocal counter result = counter counter += step return result return inner first_counter = start_count() second_counter = start_count(13, 14) print("First counter:") print(first_counter()) print(first_counter()) print("Second counter:") print(second_counter()) print(second_counter()) print("First counter:") print(first_counter()) print(first_counter()) print("Second counter:") print(second_counter()) print(second_counter())
copy

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 and second_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.

12345678910111213
def hero_hit(hero_name="Unknown"): def inner(monster="Unknown"): print("The", hero_name, "hero hit the", monster, "monster") return inner john = hero_hit("John") # use the outer argument john("Goblin") # use the inner argument john("Dinosaur") # inner("Goblin") john() # inner() john("Dragon") # inner("Dragon")
copy

Arguments passed to the inner() function behave like regular function arguments and are not related to the closure.

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

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 3
some-alt