One, what is closures:
1, function within the definition function.
2. A reference to the function when the outer function returns.
3. The inner function uses the local variable of the outer function (at least one).
1 def Outfunc (): 2 for in range (4):3 def Infunc ():4 return num*25 return Infunc
1 # Test code: 2 def Outfunc (): 3 for num in Range (4 4 def Infunc (): 5 return num*26 return
Infunc 7 8 test = Outfunc () 9 print test ()
The results are explained later.
Second, the benefits of closures:
1. Avoid using global variables
2, can provide some of the data hidden
3, can provide more elegant object-oriented implementation
Third, delay binding in closures:
Delayed binding appears to be a phenomenon but not an essence. For example, when the inner function refers to a local variable of an outer function, but the local variable is circular, then the last internal reference to the variable is actually a global variable for the inner function, so every invocation, the internal use of this variable is the last value of the loop, instead of generating one call at a time. In fact, not only the loop, but also the same variable modification. So many people understand the delay binding, the last one to bind. And it's inherently wrong.
To explain, the inner function binding is not the value of the variable of the outer function, but the address space, after the return of the external function returned is the inner function, this own local variable is still in use, will not empty the address area but save the address area, at this time, this address empty value is the last time to modify the value after the variable, Is the last value for the loop.
1 def Outfunc (): 2 temp = [lambda for in range (4)]3 return temp 4 5 for inch Outfunc (): 6 print item ()
Test results
So it's good to explain that one of the results equals 6.
Python Closures and deferred bindings