11. Closure

First Edition: without security data
l1 = [] # global variable
DEF make_average (. Price):
l1.append (. Price)
Total = SUM (L1)
return Total / len (L1)
Print (make_average (100000))
Print ( make_average (110000))
Print (make_average (120000))
'' '
has a lot of code ....
' ''
l1.append (666)
Print (make_average (90000))

Second Edition:
for each execution l1 is empty.
make_average DEF (. price):
L1 = []
l1.append (. price)
Total = SUM (L1)
return Total / len (L1)
Print (make_average (100000))
Print (make_average (110000))
Print (make_average (120000))


为了保证数据的安全,闭包

def make_average():

l1 = []
def average(price):
    l1.append(price)
    total = sum(l1)
    return total/len(l1)


return average

avg = make_average()
print(avg)>>>
<function make_average. .average at 0x0000002F02CD1268>
print(avg(100000))
print(avg(110000))
print(avg(120000))

  1. def make_average():

    count = 1
    def average():
    nonlocal count
    count += 1
    return count

    return average
    avg = make_average()

    print (avg)

    print (avg ())
    print (avg ())
    print (avg ())
    print (avg ())
    '' '
    2
    3
    4
    5
    ' ''
    `` `

Determining whether the closure:

例一:
def wrapper():
    a = 1
    def inner():
        print(a)
    return inner
ret = wrapper()
是
例二:
a = 2
def wrapper():
    def inner():
        print(a)
    return inner
ret = wrapper()
不是
例三:
def wrapper(a,b):
    '''

    :param a: 2
    :param b: 3
    :return:
    '''
    name = 'alex'
    def inner():
        print(a)
        print(b)
        age  = 'alex'
    
    return inner
a = 2
b = 3
ret = wrapper(a, b)
也是闭包

1561122503349

Analyzing a closure function is not == closure function has no free variables

print(ret.__code__.co_freevars)# ('a', 'b')
了解
print(ret.__code__.co_varnames) # 函数中的局部变量
('age',)
  • Closures: used for face questions: What is a closure? Closures have any effect.

1, the closure can only exist in nested function.

2, the inner function of the outer layer of non-global variables function 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, free variables in memory will not disappear. Closure of the role: to ensure data security.

  • How to judge a nested function without a closure

    1, the closure can only exist in nested function.

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

  • Application package closure:

    1. Ensure data security.
    2. The nature of the decorator

Guess you like

Origin www.cnblogs.com/pythonblogs/p/11100125.html