Python's deep learning closure _python

Source: Internet
Author: User
Tags closure in python

Closure (closure) is an important grammatical structure of functional programming. Functional programming is a programming paradigm (while process programming and object-oriented programming are all programming paradigms). In process-oriented programming, we have seen functions (function); In object-oriented programming, we have seen objects (object). The fundamental purpose of functions and objects is to organize code in some logical way and to improve the reusable nature of code (reusability). Closures are also a structure for organizing code, which also increases the reusable nature of code.

Different languages implement closures in different ways. Python is based on a function object and supports the syntactic structure of closures (we've seen Python use objects to implement some special syntax in special methods and multiple paradigms many times). Python is all about objects, and the grammatical structure of functions is also an object. In a function object, we use a function object like a normal object, such as changing the name of a function object, or passing a function object as a parameter.

Scope of Function objects

Like other objects, a function object has a scope for its existence, that is, the function object. function objects are defined using the DEF statement, and the function object is scoped to the same level as the def. For example, the following code, which we define in the line_conf function, can only be invoked within the LINE_CONF's membership scope.

Copy Code code as follows:

Def line_conf ():
def line (x):
Return 2*x+1
Print (line (5)) # within the scope


Line_conf ()
Print (line (5)) # Out of the scope


The Lines function defines a line (y = 2x + 1). As you can see, the line function can be called in line_conf (), while calling line outside the scope will have the following error:
Copy Code code as follows:

Nameerror:name ' line ' isn't defined

Description is already outside the scope.

Similarly, if you define a function by using a lambda, the function object's scope is the same as the level at which the lambda is located.

Closed Bag

A function is an object, so it can be returned as a result of a function.

Copy Code code as follows:

Def line_conf ():
def line (x):
Return 2*x+1
Return line # return a function object

My_line = line_conf ()
Print (My_line (5))

The above code can run successfully. The return result of the line_conf is assigned to the line object. The code above will print 11.

What happens if you refer to an external variable in the definition of line ()?

Copy Code code as follows:

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 (5))


As we can see, the subordinate program in line definition refers to the high level variable B, but the B information exists outside the definition of line (b is not defined in the subordinate program block of line). We call b the environment variable of line. In fact, line, as the return value of line_conf, already includes the value of B (although B is not part of line).

The above code will print 25, that is, the B value referenced by line is the B value that is available for reference when the function object is defined, not the B value when it is used.

A function is combined with its environment variable to form a closure (closure). In Python, the so-called closure is a function object that contains the value of an environment variable. environment variable values are saved in the __closure__ property of the function object. For example, the following code:

Copy Code code as follows:

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)

The __closure__ contains a tuple (tuple). Each element in this tuple is an object of the cell type. We see that the first cell contains the integer 15, which is the value of the environment variable B when we created the closure.

Here's a real example of a closure:

Copy Code code as follows:

Def line_conf (A, B):
def line (x):
return ax + b
Return line

line1 = line_conf (1, 1)
Line2 = line_conf (4, 5)
Print (Line1 (5), line2 (5))


In this example, the function line and the environment variable a,b constitute closures. When we create the closure, we illustrate the values of the two environment variables through the line_conf parameter a,b, so that we determine the final form of the function (y = x + 1 and y = 4x + 5). We only need to transform the parameter a,b, we can get different line expression functions. Thus, we can see that closures also have the function of improving code reusability.

If there is no closure, we need to specify a,b,x each time we create a line function. In this way, we need more parameter passing and less portability of code. With closures, we actually created the functionals. The line function defines a function that is broadly meaningful. Some aspects of this function have been identified (must be straight lines), but others (such as a and B parameters to be determined). Then, we determine the final function by the form of closure, according to the parameters passed by the line_conf.

Closures and parallel operations

Closures effectively reduce the number of parameters that a function needs to define. This is of great significance for parallel operations. In the parallel computing environment, we can have each computer responsible for a function, and then the output of a computer and the next computer input series. In the end, we work like pipelining, inputting data from one end of a series of computer clusters and outputting data from the other. Such situations are best suited for functions that have only one parameter input. Closures can be used to achieve this.

Parallel operations are referred to as a hotspot. This is also an important reason for functional programming to heat up. Functional programming has existed in the early 1950, but it is not widely used. However, the pipelined work parallel clustering process described above is suitable for functional programming. Because of the natural advantage of functional programming, more and more languages are becoming more and more supportive of functional programming paradigms.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.