Talking about the closure in Python and talking about the closure in Python
In my opinion, the concept of closure in Python is equivalent to defining one or more functions in a function. The inner function defines the specific implementation method, this implementation method is returned for the outer function, but it is not executed unless the inner implementation method called by the outer function is executed. The following example shows how to execute this operation.
For example:
Def sum_outer (x, y): def sum_in (z): return x + y-z; return sum_in # note that the returned result is not sum_in () only m = sum_outer (3, 4) #3, 4 correspond to x and y respectively. Here m returns only the definition of the sum_in function, <function _ main __. sum_in> print m (5) # m corresponds to z. This is the actual execution of sum_in.
It looks like calling the sum_in function of the inner layer through sum_outer, with more layer proxies
One of the application scenarios is that different results can be returned using the same implementation based on different parameters. For example, different database connections can be obtained based on different configurations, alternatively, you can verify the length of a string based on the maximum length (the maximum length of the outer layer and the string passed by the inner layer ).
In abstraction, the outer layer defines an environment, and the inner layer is what to do in the environment, but this is not done yet,
Just to do. When you really need to do it, you can do it in this environment (the returned result of the outer layer (m) executes the function sum_in of the inner layer)
In fact, directly pass all the required parameters to the function and directly return the result. The above sum_outer and sum_in are directly passed through
Def sum (x, y, z): return x + y-z
Isn't it done? Why do we need to implement closure? For the time being, we can only see that they are two different implementation methods, more differences, and the learning experience that will be available in the future.
The above is all the content of this article. I hope you will like it.