Example of how to use a function (closure) in a Python function.

Source: Internet
Author: User

Example of how to use a function (closure) in a Python function.

This example describes how to use the Python closure. We will share this with you for your reference. The details are as follows:

You can also define functions, that is, closures, in Python functions. Similar to the closure concept in js, here is an example of closure in Python.

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: 123 and 144.

Why? In Python, everything is an object. Execute p (100), where p is the make_adder (23) object, that is, the addend parameter is 23, and you pass in another 100, that is, the augend parameter is 100, and the sum of the two is 123, and return.

Have you found that the make_adder function defines a closure function, but the return returned by make_adder is the name of the closure function, which is a 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()

Running result:

tantengdeMacBook-Pro:learn-python tanteng$ python3 closure.py Hello, ma6174 , 1 access!Hello, ma6174 , 2 access!Hello, ma6174 , 3 access!

The counter function is implemented using the closure, which is also a feature of the closure. The returned values are stored in the memory, so the counting function can be implemented.

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.