mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 09:41:36 +00:00
[python/en] adding an example for closures in python where we use the nonlocal
… (#4033)
* adding an example for closures in python where we use the `nonlocal` keyword Adding an example for the case of nested functions with closure scopes, when we use the python 3s keyword 'nonlocal' to point to the variables in the outer functions * Formatting Comments
This commit is contained in:
parent
58d91b0ba3
commit
05aa44a041
@ -655,6 +655,22 @@ def create_adder(x):
|
||||
add_10 = create_adder(10)
|
||||
add_10(3) # => 13
|
||||
|
||||
# Closures in nested functions:
|
||||
# We can use the nonlocal keyword to work with variables in nested scope which shouldn't be declared in the inner functions.
|
||||
def create_avg():
|
||||
total = 0
|
||||
count = 0
|
||||
def avg(n):
|
||||
nonlocal total, count
|
||||
total += n
|
||||
count += 1
|
||||
return total/count
|
||||
return avg
|
||||
avg = create_avg()
|
||||
avg(3) # => 3.0
|
||||
avg(5) # (3+5)/2 => 4.0
|
||||
avg(7) # (8+7)/2 => 5.0
|
||||
|
||||
# There are also anonymous functions
|
||||
(lambda x: x > 2)(3) # => True
|
||||
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||
|
Loading…
Reference in New Issue
Block a user