Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!
Closure (closure)It is an important syntax structure for functional programming. Functional programming is a programming paradigm (both process-oriented and object-oriented programming are programming paradigms ). In process-oriented programming, we have seen functions; in object-oriented programming, we have seen objects ). The fundamental purpose of functions and objects is to make some logic.OrganizationCodeAnd improve the CodeReusability(Reusability ). Closure is also a structure for organizing code, which also improves code reusability.
Different Languages implement closures in different ways. Python usesFunction objectTo provide support for the closure syntax structure.Special methods and multi-paradigm). Python is an object. The syntax structure of a function is also an object. InFunction object.
Function object scope
Like other objects, a function object also has its survival range, that is, the function object'sScope. Function object is usedDefThe scope andDefThe level is the same. For example, in the following code, the line function defined in the scope of the line_conf function can only be called within the scope of the line_conf function.
DefLine_conf ():DefLine (x ):Return2 * x + 1Print(Line (5 ))#Within the scopeLine_conf ()Print(Line (5 ))#Out of the Scope
The line function defines a straight line (y = 2x + 1 ). We can see that the line function can be called in line_conf (), and the following error will occur when line is called out of scope:
Nameerror: Name 'line' is not defined
It indicates that it is out of scope.
Similarly, if you useLambdaDefine a function, so the function object scope is the same as that of Lambda.
Closure
A function is an object, so it can be used as a functionReturned results.
DefLine_conf ():DefLine (x ):Return2 * x + 1ReturnLine# Return a function objectMy_line=Line_conf ()Print(My_line (5 ))
The above code runs successfully. The result returned by line_conf is assigned to the line object. The above code will print 11.
What happens if the definition of line () References external variables?
DefLine_conf (): B= 15DefLine (x ):Return2 * x +BReturnLine#Return a function objectB = 5
My_line=Line_conf ()Print(My_line (5 ))
We can see that the line-defined affiliationProgramThe block references the High-Level variable B, but the B information exists outside the line definition (the B definition is not in the line membership block ). We call B lineEnvironment Variable. In fact, when line is the return value of line_conf, line already contains the value of B (although B is not affiliated with line ).
The above code will print 25, that is, the B value referenced by line isB value that can be referenced when the function object is definedInstead of the B value used.
A function is combined with its environment variables to formClosure (closure). In python, a closure is a function object that contains the values of environment variables. The value of the environment variable is stored in_ Closure __Attribute. For example, the following code:
def line_conf (): B = 15 def line (x): return 2 * x + B return line # return a function object B = 5 my_line = line_conf () Print (my_line. __ closure __ ) Print (my_line. __ closure __ [0]. cell_contents)
_ Closure _ contains a tuple ). Each element in this tuples isCellType object. We can see that the first cell contains an integer of 15, that is, the value of environment variable B when we create a closure.
The following is an example of a closure:
DefLine_conf (A, B ):DefLine (x ):ReturnAx +BReturnLineline1= Line_conf (1, 1)
Line2 = line_conf (4, 5)Print(Line1 (5), line2 (5 ))
In this example, the line function and the environment variables A and B constitute the closure. When creating a closure, we use the line_conf parameters A and B to describe the values of these two environment variables. In this way, we have determined the final form of the function (y = x + 1 and Y = 4x + 5 ). We only need to transform the parameters A and B to obtain different linear expression functions. As a result, we can see that closures also improve code reusability.
If no closure exists, we need to describe a, B, and X each time we create a linear function. In this way, we need more parameter passing and reduce code portability. Using closures, we actually createdFunctional. The line function defines a function of broad significance. Some aspects of this function have been determined (must be a straight line), but other aspects (such as parameters A and B to be determined ). Then, we determine the final function in the form of a closure based on the parameters passed by line_conf.
Closure and parallel operations
The closure effectively reduces the number of parameters required for the function. This is of great significance for parallel operations. In a parallel computing environment, we can let each computer take charge of a function, and then connect the output of a computer with the input of the next computer. In the end, we work like an assembly line to input data from one end of the connected computer cluster and output data from the other end. Such a situation is most suitable for functions with only one parameter input. Closure can achieve this purpose.
Parallel operations are called hot spots. This is also an important reason for the popularity of functional programming. Functional Programming already exists in the 1950 s, but it is not widely used. However, the assembly-line working parallel cluster process described above is suitable for functional programming. Due to the natural advantage of functional programming, more and more languages have begun to support the functional programming paradigm.
Welcome to continue reading the "Python quick tutorial""