Learning about Python closures

Source: Internet
Author: User

learning about Python closures


What is a closure package?

Borrowed from the wiki: in Computer science, closures (Closure) are short for lexical closures (Lexical Closure) and are functions that reference free variables. This quoted free variable will exist with this function, even if it has left the environment in which it was created. So, there is another argument that closures are entities that are composed of functions and their associated reference environment. Closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.

Well, looking at this definition is not yet an immediate understanding of what closures are. However, closures are not difficult to understand, and a few small examples can be seen to clarify what it is.

Prerequisite Introduction:

Before we know about closures, we need to understand the scope of the variables in the Python syntax (it helps to understand the examples behind closures). Python supports multiple function nesting from syntax. In Python's existing (post 2.1) nesting rules, nested functions can access the scope of the global scope itself and the local scope of the function above itself. such as (from the Python Core programming book):

Variable Range Example one:

x = 1def foo (): y = 2def bar (): Z = 3print x + y + zbar () foo ()

The result is output:

6

Explain:

That is, the bar () function can access the global variable x, its own local scope Z, and can also access the local variable y that nests its own foo () function.

Next, we need to know that in python2.x, the inner function can access the variables of the outer function, but it cannot be assigned a value. We make a slight modification to the example:

Variable Range example two:
x = 1def foo (): y = 2def bar (): z = 3y + = 1print x + y + zbar () foo ()

Results:

At this point the operation will be error: unboundlocalerror:local variable ' y ' referenced before assignment.

This error means that the local variable y is not defined before the reference. This is because when assigning variables in the inner function, Python will assume that the variable is local, so if the value of the modified variable becomes a local variable (if not, of course, Python will first look within its own definition, if not, So we know that Y is an outer variable).

This can be solved using nonlocal in Python 3.x, where the nonlocal keyword is used to use outer (non-global) variables in functions or other scopes.

After understanding the scope of variables in Python, let's look at a couple of closures (from the Python Core programming book):

Closure Example One:
def counter (start_at=0): Count = [Start_at]def incr (): count[0] + = 1 return count[0]return incr

Results:

>>> count = Counter (5) >>> print count () 6>>> print count () 7>>> Count2 = counter (100) & gt;>> Print Count2 () 101
Explanation:

In the counter function, we define a incr function, the function of the INCR function is to add a value of count[0], counter function return incr function. Note that in Python all order objects, functions can also be passed and returned as function objects.

When we execute Count = Counter (5), Count is given the INCR function object, which means that the call to count is equivalent to calling the INCR function. In addition, we give the counter function a parameter of 5, then the initial value of Count[0] is 5, the return to the given parameter of the function object assigned to count, then each call to count will execute count[0] plus one, and return the value of count[0].

In summary, we can see that the counter () function has different parameters, the resulting function object is not the same, that is, we can use this form to bind the function and a parameter to assign to an object, and then through the object to do related operations.

Note: It is not possible to change the count in counter () from the list to a single variable, otherwise the Unboundlocalerror error will be reported (the prerequisites explain why), but the list can.

Closure Example II:
def xy_add (x):d ef Adding (y): #根据前面的函数嵌套变量作用域介绍, you should know adding () can access Xreturn x + Yreturn adding

Results:

>>> Myadd = Xy_add (3) >>> print Myadd (4) 7>>> print Myadd (3) 6


Explain:

The Xy_add () function will scope its nested adding function object, when we give the Xy_add () function argument, such as given XI, and assign the function object returned under this parameter to Myadd, Myadd is a function with a specific parameter, by calling Myadd (Yi ), we can get any sum of the sums of Xi and Yi.

meaning and Effect:

To tell the truth, I beginner python, not how to use the closure, JavaScript is used, but the impression is not deep. Here are excerpts from other people's views on the Internet.

The fundamental purpose of 1> functions and objects is to organize the code in some logical way and to improve the reusable nature of the code. Closures are also a structure of the organization code, which also improves the reusable nature of the code. Source.

2> When the closure is executed, the current operating environment is still maintained. For example, in the process of controlling a chess piece, the closure can be calculated using the last piece coordinate. Source.

3> closures can get different results based on the local variables of the outer scope, which is a bit like the function of a configuration function, we can modify the external variables, closures according to this variable to show different functions. For example, sometimes we need to analyze the special lines of some files to extract these special lines first. Source.

4> is advantageous to parallel operation, analogy decorator function and so on.


Learning about Python 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.