Let's look at a simple function.
1 def Calc_sum (1st):
2 def lazy_sum ():
3 return sum (1st)
4 return Lazy_sum
At this point it is not able to move the lazy_sum to the outside of the calc_sum because it references the calc_sum parameter lst.
Such an inner layer function refers to the variable of the outer function (parameter is also a variable). It then returns the case of the inner layer function, called the closure (closure).
The feature of closures is that the returned function also refers to the local variables of the external function, so to properly use closures, it is necessary to ensure that the referenced local variables do not change after the function returns.
Down we'll see a case that should be understood:
The actual results are all 9.
The reason is that when the count () function returns three functions, the value of the variable I referenced by these three functions has become 3, and since F1,F2,F3 is not called, they do not calculate i*i, when F1 is invoked: The result is 9.
Therefore, the return function does not drink any loop variables, or subsequent variables that change loudly.
After rewriting the count () function like this, he can return 149 correctly.
Understanding closures through Python