Lane closures python

"Closure by an entity associated reference function and the components of the environment", simply put, is nested within the definition of a function in an external function, and the function referenced outside the local variables in the function, and the outer the inner layer functions as a function of return value to the caller, then the return value is a closure

Example:

def outer(x):
    def inner():
        nonlocal x
        x += 1
        return x
    return inner

The above is a nested function, when invoked outer closure will give a return function, the closure Inner contains the function () and the reference function of external variables X, the closure is an object, which is variable equivalent to internal members of an object

When closure following code is executed to call e.g.

a = outer(1)
b = outer(2)

print(a(), b())
print(a(), b())

The result will be:

2 3
3 4

The reason is simple, a closure object is a, b is a closure object, ab just of the same "type" of closure object, there is no relationship between them, and when a call, a closure member values ​​of x plus 1, while no effect on the closure of the x members b, b when the call only to members within b, x plus 1, and when the second call to a closure, due to the time before the first call has been added 1 , so called again and add 1, b empathy

another situation

def outer():
    fs = []
    for i in range(3):
        def inner():
            return i
        fs.append(inner)
    return fs

a, b, c = outer()
print(a(), b(), c())

The desired result is 0, 1, 2, and the actual result of 2, 2, 2

The reason is simple, the closure is to generate the time out function return, when the outer case of the function return value is found to satisfy the return closures, it will be required for the local variables closing function bound to the outer closure because it is generated to return the closure when the closure so that when the reference value is the return value of the variable inside, rather than the value of the time append

Guess you like

Origin www.cnblogs.com/max88888888/p/11128599.html