Getting Started with Python's closure

Getting Started with Python's closure

1, the closure

(1) (the present non-variable layer) and non-global variables in the nested function is the closure

(2) _ closure _ closure is not determined

def func():
    a = 1
    def foo():
        print(a)
    print(foo.__closure__)  # 判断是不是闭包
func()
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):
    def inner():
        print(a)
        print(b)
    inner()
    print(inner.__closure__)
a = 1
b = 2
wrapper(11,22)

(3) closure of the effect:

<1> Save local information is not destroyed, to protect data security

<2> in decorator

(4) closure applications:

<1> can be stored non-global variables but is not easily destroyed, the changed data.

<2> In the decorator

Guess you like

Origin www.cnblogs.com/caiyongliang/p/11445058.html