When the returned internal function uses the variables of the external function, it forms a closure
Closures can save variables of external functions , It can also improve the reusability of code
Realize the standard format of closures :
1. Nested function
2. Internal functions use variables or parameters of external functions
3. The external function returns the internal function
# @Author : Kant
# @Time : 2022/1/23 17:19
'''
When the returned internal function uses the variables of the external function, it forms a closure
Closures can save variables of external functions , It can also improve the reusability of code
Realize the standard format of closures :
1. Nested function
2. Internal functions use variables or parameters of external functions
3. The external function returns the internal function
'''
# Define a closure
def outer(): # External function
n=1
def inner(): # Internal function
print(n)
# The outer function returns a reference to the inner function ( No parentheses )
return inner
outer() # Calling an outer function does not execute an inner function
# inner() # Inner functions cannot be called directly
ret=outer() # Give a reference to an inner function ret
print(ret)
ret()
# Use of closures
def person(name):
def say(msg):
print(f'{name} say: {msg}')
return say
tom=person('Tom')
rose=person('Rose')
tom('Hello')
rose('World')
# @Author : Kant
# @Time : 2022/1/23 17:55
def outer():
n=1
def inner():
nonlocal n # No mistake will be reported , list 、 Dictionaries 、 Yuanzu doesn't need to add
n=n+10
print(n)
print(n) # Output 1
return inner
fun=outer()
fun() # Output 11
fun() # Output 21