Examples of closure usage in python and examples of python usage

Source: Internet
Author: User

Examples of closure usage in python and examples of python usage

This example describes the closure usage in python. Share it with you for your reference. The specific analysis is as follows:

What is a closure?

To put it simply, closures get different results based on different configuration information.

Let's take a look at our professional explanation: Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment.

Python instance:

Looking at concepts is always confusing. Just look at a few small python examples.

Example 1

def make_adder(addend):  def adder(augend):    return augend + addend  return adderp = make_adder(23)q = make_adder(44)print p(100)print q(100)

Running result:

123144

Analysis:

We found that make_adder is a function, including the addend parameter. In particular, this function defines a new function, A variable in this new function is exactly the parameter of the external make_adder. that is to say, the addend parameter passed externally has been bound with the adder function to form a new function. We can regard addend as a configuration information of the new function. The configuration information is different, functions are different, that is, the customized functions can be obtained.

Looking at the running results, we found that although p and q are both generated by make_adder, different results are obtained after executing the functions with the same parameters due to different configuration parameters. this is the closure.

Example 2

def hellocounter (name):  count=[0]   def counter():    count[0]+=1    print 'Hello,',name,',',str(count[0])+' access!'  return counterhello = hellocounter('ma6174')hello()hello()hello()

Execution result

Hello, ysisl , 1 access!Hello, ysisl , 2 access!Hello, ysisl , 3 access!

Analyze

This program is interesting. We can regard this program as a function for counting the number of function calls. count [0] can be regarded as a counter. If the hello function is not executed once, the value of count [0] is increased by 1. Maybe you have a question: why does it use a list instead of Directly Writing count? This is a bug in python2. If the list is not used, the following error will be reported:

UnboundLocalError: local variable 'Count' referenced before assignment.

What does it mean? That is to say, the conut variable is referenced directly without definition. I don't know what it is, and the program crashes. therefore, in python3, a keyword: nonlocal is introduced. What is this keyword? It is to tell the python program that my count variable is defined externally. You can find it outside. then python finds the outer function and finds the definition and value assignment of count = 0, and the program can be executed normally.

Python3 code

def hellocounter (name):  count=0   def counter():    nonlocal count    count+=1    print 'Hello,',name,',',str(count[0])+' access!'  return counterhello = hellocounter('ma6174')hello()hello()hello()

Example 3

def makebold(fn):  def wrapped():    return "<b>" + fn() + "</b>"  return wrappeddef makeitalic(fn):  def wrapped():    return "<i>" + fn() + "</i>"  return wrapped@makebold@makeitalicdef hello():  return "hello world"print hello()

Execution result

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

Simple Analysis

How is it? Is this program familiar? Isn't this a legend of decorator? Yes, this is the decorator. In fact, the decorator is a closure. Let's look back at the concept of the decorator: processing functions (parameters, return values, etc, generate a function of the Enhanced Function version. Let's look at the concept of closures. Isn't the enhanced function the function we configured? The difference is that the parameter of the decorator is a function or class, which is specialized in processing classes or functions.

Many advanced functions in python, such as the decorator, generator, list push, closure, and anonymous functions, can be used in development to get twice the result with half the effort!

I hope this article will help you with Python programming.

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.