""" Closure definition : 1. A closure is a function nested in a function . 2. Closures must be variables of inner functions and outer functions ( Non global variables ) Reference or change of ( Changing immutable data types requires keywords nonlocal Declare in the inner function , Variable data types do not nonlocal Statement , Directly modifying ). Properties of closures : The space of a closure function does not disappear with the end of the function ; Variables that are referenced or changed do not disappear The function of closures : Keep local information not destroyed , Ensure data security . Application of closures : 1、 Some non global variables can be saved but not easily destroyed 、 Changed data . 2、 The essence of ornaments . """
def averageWrapper():
# The space of a closure function does not disappear with the end of the function ; Variables that are referenced or changed do not disappear
l = []
def averageInner(nums:int):
l.append(nums)
total = sum(l)
return total / len(l)
return averageInner
ret = averageWrapper()
print(ret(10)) # 10.0
print(ret(20)) # 15.0
print(ret(30)) # 20.0
print(ret(40)) # 25.0
# Judge whether a function is a closure : Whether the closure function has free variables
print(ret.__code__.co_freevars) # ('l',)