Functions in Python functions (examples of closures)

Source: Internet
Author: User
Tags closure in python

Python instance

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

Example 1

def make_adder (addend):
def adder (augend):
return augend + addend
Return adder

p = Make_adder (23)
Q = Make_adder (44)

Print P (100)
Print Q (100)
Run Result:

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

def hellocounter (name):
COUNT=[0]
Def counter ():
Count[0]+=1
print ' Hello, ', Name, ', ', str (count[0]) + ' access! '
Return counter

Hello = Hellocounter (' ma6174 ')
Hello ()
Hello ()
Hello ()
Execution results

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

def hellocounter (name):
Count=0
Def counter ():
nonlocal count
Count+=1
print ' Hello, ', Name, ', ', str (count[0]) + ' access! '
Return counter

Hello = Hellocounter (' ma6174 ')
Hello ()
Hello ()
Hello ()
For the study of this problem you can refer to http://linluxiang.iteye.com/blog/789946

Example 3

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 Hello ()
Execution results

<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!

A function can also be defined in a Python function, which is a closure. And JS in the closure concept is actually similar to, for example in Python closures.


def make_adder (addend):
def adder (augend):
return augend + addend
Return adder

p = Make_adder (23)
Q = Make_adder (44)

Print (P (100))
Print (q (100))
The results of the operation are: 123 and 144.


Why? Everything in Python is an object, executing p (100), where p is the object of Make_adder (23), that is, addend this parameter is 23, you pass in a 100, that is, the Augend parameter is 100, and the two add 123 and return.

Have you found make_adder this function, which defines a closure function, but the return returned by Make_adder is the inside of the closure function name, which is the characteristics of the closure function.

Let's look at a python closure example:


def hellocounter (name):
COUNT=[0]
Def counter ():
Count[0]+=1
Print (' Hello, ', Name, ', ', count[0], ' access! ')
Return counter

Hello = Hellocounter (' ma6174 ')
Hello ()
Hello ()
Hello ()

Run Result:

Tantengdemacbook-pro:learn-python tanteng$ Python3 closure.py
Hello, ma6174, 1 access!
Hello, ma6174, 2 access!
Hello, ma6174, 3 access!

The use of closures to achieve the function of the counter, which is also a feature of the closure, the return value saved in memory, so you can implement the counting function.

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.