Examples of closed-pack usages in Python

Source: Internet
Author: User
Tags closure pack in python

This article mainly introduces the usage of the closure in Python, and analyzes the concept of the closure in Python in detail and the related usage skills, which has some reference value, and the friends who need it can refer to the following

The examples in this article describe the use of closures in Python. Share to everyone for your reference. The specific analysis is as follows:

What is a closure?

Simply put, closures are based on different configuration information to get different results

A second look at the professional explanation: Closure (Closure) is a lexical closure (lexical Closure) abbreviation, is a reference to the function of the free variable. The referenced free variable will exist with this function, even if it has left the environment that created it. So, there is another saying that closures are entities that are combined by functions and reference environments associated with them.

Python instance:

It's always a little confusing to look at the concept, so just look at a few Python examples.

Example 1

?

1 2 3 4 5 6 7 8 def make_adder (addend): def adder (augend): return augend + addend return adder p = make_adder (MB) q = Make_adder () print P (m) print Q (100)

Run Result:

?

1 2 123 144

Analyze:

We found that the Make_adder is a function, including a parameter addend, the special place is that this function also defines a new function, the new function inside a variable is exactly the external make_adder parameters. In other words, The externally passed Addend parameters have been bound together with the Adder function, forming a new function, we can see addend as a new function of the configuration information, configuration information is different, function is not the same, that is, can be customized after the function.

Looking at the results of the run, we found that although P and Q were make_adder generated, different results were obtained because the configuration parameters were different and then the function of the same parameter was followed. This is the closure.

Example 2

?

1 2 3 4 5 6 7 8 9 10 def hellocounter (name): Count=[0] def counter (): Count[0]+=1 print ' Hello, ', Name, ', ', str (count[0]) + ' access! ' return cou nter Hello = hellocounter (' ma6174 ') hello () hello () hello ()

Execution results

?

1 2 3 Hello, YSISL, 1 access! Hello, YSISL, 2 access! Hello, YSISL, 3 access!

Analyze

This program is interesting and we can think of this as a function that counts the number of times a function is called. Count[0] can be seen as a counter, the Hello function is not executed once, and the value of count[0] is added 1. Maybe you have a question: Why not write count directly and use a list? This is a bug in Python2, and if you don't use a list, you'll report an error:

Unboundlocalerror:local variable ' count ' referenced before assignment.

What do you mean by that? conut this variable you have no definition of the direct reference, I do not know what it is, the program crashed. So, again python3 inside, introduced a keyword: nonlocal, what is this keyword? is to tell the Python program, My count variable is externally defined, so go outside and look for it. Then python goes to the outer function and finds the COUNT=0 definition and assignment, and the program executes normally.

Python3 Code

?

1 2 3 4 5 6 7 8 9 10 11 def hellocounter (name): count=0 def counter (): nonlocal count count+=1 print ' Hello, ', Name, ', ', str (count[0]) + ' access! ' r Eturn Counter Hello = Hellocounter (' ma6174 ') hello () hello ()

Example 3

?

1 2 3 4 5 6 7 8 9 10 11 12-13 def makebold (FN): Def wrapped (): Return "<b>" + fn () + "</b>" return wrapped def makeitalic (FN): Def wrapped () : Return ' <i> ' + fn () + "</i>" return wrapped @makebold @makeitalic def hello (): Return to "Hello World" Print he Llo ()

Execution results

?

1 <b><i>hello world</i></b>

Simple analysis

What do you think? Is this program familiar? Isn't this a legendary decorator? Yes, this is the adorner, in fact, the adorner is a closure, we recall the concept of the adorner: function (parameters, return value, etc.) for processing, to generate a function enhanced version of a function. And looking at the concept of closures, this enhanced version of the function is not what we configure after the function? The difference is that the adorner's argument is a function or class that specializes in processing a class or function.

Python inside a lot of advanced features, such as adorners, generators, list push, closures, anonymous functions, and so on, the development of use, may achieve a multiplier effect!

I hope this article will help you with your Python programming.

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.