Closure: In programming versions, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment-a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.
In my understanding, closures are entities combined by functions and their referenced environments. The closure function references non-local variables, which are bound to the values of these non-local variables in the reference environment.
Let's look at several examples.
1. What is the output of the following code?
The code is as follows: |
Copy code |
Flist = [] For I in xrange (3 ): Def func (x ): Return x * I Flist. append (func) For f in flist: Print f (2) |
In fact, every printing is 4, because here is a closure, I forms a closure together in the reference environment of the func function, and I is gradually changed to 2, func is referenced by I, therefore, when f (2) is called, the value of I is 2, and f (2) returns 4.
2. What is the output of the following code?
The code is as follows: |
Copy code |
Def generate_power_func (n ): Def nth_power (x ): Return x ** n Return nth_power If _ name _ = '_ main __': Raised_to_4 = generate_power_func (4) Del generate_power_func Print raised_to_4 (2) |
The output is 16. because n is part of the reference environment in the closure, even if the life cycle of generate_power_func ends, the closure still can be called to n = 4 in raise_to_4 (2.
If you do not want to use the closure feature, you can define external variables as a container, such as dict and list, as shown in the following example:
The code is as follows: |
Copy code |
Def outer (): D = {'Y': 0} Def inner (): D ['Y'] + = 1 Return d ['Y'] Return inner Def foo (): A = [1,] Def bar (): A [0] = a [0] + 1 Return a [0] Return bar If _ name _ = '_ main __': Outer = outer () Print outer () Foo = foo () Print foo () |
In python3, a variable can be modified with the nonlocal keyword in the internal function to identify a variable as a non-local variable.
The sample code for this article is in: https://github.com/smilejay/python/blob/master/py2014/closure.py