Closures in Python, peer access of closures, and state of parameters saved by closures
1. Introducing a closure.
First of all, one problem is that we cannot access the variable a inside the function outside the function .
But we can use return to return the value of this variable, and there must be a container to follow.
Here, the variable a and the function inner_func are siblings . Similarly, we can use return to throw this internal function out, and then use a container to follow it.
So, the format of the closure:
1. The internal function is defined in the external function.
2. The external function has a return value.
3. The returned value is the name of the internal function.
4. The internal function refers to the variable of the external function, otherwise it is not a complete closure.
2. The same-level access of the closure and the state of the closure save parameters
(1) The scope of the same level can be used, but the variables in the same level cannot be used. For example, if you print the variable b in inner_func1 in inner_func2, an error will be reported, but inner_func1() can be called in inner_func2
(2) Read the internal variables of other elements
(3) Extend the scope
Let’s look at a piece of code first. After calling the external function and passing in 2, 3, we didn’t immediately call x(), which is the internal function. Instead, we called the external function again and passed in 4, 5 before calling the internal function.
From the results, we can see that the closure can save the state of the outer function variables . To put it simply, when func(2,3) is called, the internal function of return has recorded and saved the values of a and b at this time, and In the last execution of x(), the values of a and b will not be overwhelmed by 4 and 5 the second time.
3. Disadvantages of closures
(1) The scope is not so intuitive
(2) Because variables will not be garbage collected, there is a little memory occupation problem
4. Summary of closures
(1) Closures optimize variables. The work that originally required class objects to complete can also be completed
by closures. (2) Since closures introduce local variables of external functions, local variables of external functions are not timely Release and consume memory
(3) Closures make the code concise and easy to read
(4) Closures are the basis for understanding decorators
5. Application: Counter
This is the execution of 68 lines of code. When the internal function is called for the second time, it is found that after the first call to the internal function, the variable container at the same level as the internal function has changed from [0] to [1].