Chapter V of the python function (9): Closures

What is closure?
Let's give chestnut: the built-in functions external call functions (nested functions normally function on the outside is not visible)

def outer():
    a1 = 'test arg'

    def inner():
        print('inner', a1)

    return inner  # 注意,这里返回的是inner函数的内存地址,而不是执行结果。执行结果需要带()。


func = outer()  # outer()的执行结果返回inner的内存地址,相当于inner

func()  # 这里func加()相当于inner()。这样就可以在外部调用内部的函数了。

In principle, the function is finished, the function of all the variables should be released. However, the above-described embodiment, outer performed after, a1 variable and not released.
Why is this?

Because the inline function inner () is func () call on the outside, so that the enclosing outer () function scope can not be released. So inner () return value of the variable a1 can still call the outer () is. This phenomenon we call closure.

  • Closure meaning: inline function returns the object is not only a function object, outside the scope function also wrapped in a layer (the enclosing), so that no matter where the function call, the limited scope of their use in outer wrap

  • Features: return built-in functions

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11076888.html