Python deep 04 Closures

Source: Internet
Author: User
Tags closure

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

Different languages implement closures in different ways. Python is based on a function object and provides support for the syntactic structure of closures (we have seen Python use objects for some special syntax in special methods and multiple paradigms). Python everything is object, function This syntax structure 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 object

Like other objects, a function object has its own scope, that is, the scope of the function object. A function object is defined with a def statement, and the scope of the function object is the same as the level at which the def resides. For example, the following code, which is defined within the membership scope of the LINE_CONF function, can only be called within the LINE_CONF's membership range.

def line_conf ():     def Line (x):         return 2*x+1    print(line (5))   #  within the scopeline_conf ()  Print(line (5))       # out of the scope

The line function defines a linear (y = 2x + 1). As you can see, the line function can be called in line_conf (), and calling line outside the scope will have the following error:

Nameerror:name ' line ' isn't defined

The description is now outside the scope.

Similarly, if you use lambda to define a function, the scope of the function object is the same as the level at which the Lambda resides.

Closed Package

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

def line_conf ():     def Line (x):         return 2*x+1    return# return a function object= 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 above code will print 11.

What happens if the external variables are referenced in the definition of line ()?

def line_conf ():     =    def line  (x):        return 2*x+b    return line       #  return a function objectB = 5
= line_conf ()print(My_line (5))

As we can see, the line definition of the subordinate program block refers to the high-level variable B, but B information exists outside the definition of line (b is not defined in the line's membership block). We call b the environment variable for line. In fact, when line is the return value of line_conf, the value of B is included in line (although B is not affiliated with line).

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

When a function is combined with its environment variables, it forms a closure (closure). In Python, the so-called closure is a function object that contains the value of an environment variable. The environment variable value is stored in the __closure__ property of the function object. For example, the following code:

def line_conf ():     =    def line  (x):        return 2*x+b    return line       #  return a Function object= 5= 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 type cell . We see that the first cell contains the integer 15, which is the value of the environment variable B when we created the closure.

Let's look at a practical example of a closure:

def line_conf (A, B):     def Line (x):         return a*x + b    return= line_conf (1, 1)
Line2 = line_conf (4, 5)print(line1 (5), line2 (5))

Python deep 04 Closures

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.