Example of a function (closure) usage in a Python function

Source: Internet
Author: User
The examples in this article describe the use of Python closures. Share to everyone for your reference, as follows:

Functions can also be defined in Python functions, i.e. closures. In fact, the concept of closure in JS is about the same as in the case of a python closure.

def make_adder (addend):  def adder (augend):    return augend + addend  return adderp = Make_adder (all) Q = Make_ Adder (+) print (P (+)) print (q (100))

The results are: 123 and 144.

Why? In Python all objects, execute P (100), where P is make_adder (23) This object, that is, addend this parameter is 23, you pass in a 100, that is, the Augend parameter is 100, the two add 123 and return.

Did you find make_adder this function, which defines a closure function, but the return returned by Make_adder is the name of the closure function inside, which is the feature 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 Counterhello = Hellocounter (' ma6174 ') hello () hello () hello ()

Operation 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 implement the function of the counter, which is a feature of closures, the returned value is stored in memory, so you can implement the Count function.

Turn from: Small Talk blog http://www.tantengvip.com/2015/07/python-closure/

I hope this article is helpful for Python program design.

  • 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.