Python closure a free variable

Understanding: closed things: to ensure data security

#平均收盘价 方案一		数据是不安全的
l1 = []
def make_average(new_value):
    l1.append(new_value)
    total = sum(l1)
    average = total / len(l1)
    return average	
*************************************************************
#方案二:闭包
def make_average():
    l1 = []	#自由变量
    def aver(new_value):		#闭包
        l1.append(new_value)
        total = sum(l1)
        average = total / len(l1)
        return average
    return aver
avg = make_average()
avg(100000)
avg(110000)

Closure definitions :

1. nested closure function only in the presence of

2. The function of the inner function of the outer layer of the non-global variable is referred (used), it will form a closure.

Non-global variables are referenced, also known as free variables, the free variables will produce a binding relationship with the inner function,

That is, free variables in memory will not disappear.

Closure of the role : to ensure data security

How to judge a nested function without a closure :

def make_average():
    l1 = []	#自由变量
    def aver(new_value):		#闭包
        l1.append(new_value)
        total = sum(l1)
        average = total / len(l1)
        return average
    return aver
avg = make_average()
#__code__.co_freevars 查看函数中自由变量的方法 如果有自由变量 即为闭包
avg.__code__.co_freevars #  查看函数的自由变量(l1,)

Guess you like

Origin www.cnblogs.com/pandaa/p/12053291.html