Small ape circle python learning - what closures are?

On the closure, i.e., function definitions and function in vivo function expressions located (nested function) to another function. Moreover, these internal functions can access all the local variables of the outer function which they declared parameters. When one of these internal functions are called outside the external function comprising them, it will form the closure. That is, the internal function will be executed after the outer function has returned. When this internal function is executed, it is still necessary to access external functions of local variables, parameters, and other internal functions. The values ​​of these local variables, parameters, and function declarations (initially) is a value when the external function returns, but also affected by the internal functions.

def outer():

    name = 'alex'

    def inner():

        print ( "Print the outer function in the inner lining of the variables", name)

    return inner # Note that only return inner memory address, not implemented

f = outer() # .inner at 0x1027621e0>

f () # is equivalent to the implementation of inner ()

Note that at this time outer have been implemented, under normal circumstances in the outer memory have been released, but this time because of closures, we can still call the inner, and inner interior also call on the outer layer of the variables in the name . This phenomenon is sticky gooey closure.

Significance closures: the function returns an object, not just a function object, outside the scope function also wrapped in a layer, which makes the function calls regardless of where, preferentially the outer layer wrapped their scope

Closures which will be used? The following section will use.

Reproduced in: https: //www.jianshu.com/p/946d29a6ad4f

Guess you like

Origin blog.csdn.net/weixin_33695082/article/details/91100222