Python closure: return function usage example, python example

Source: Internet
Author: User

Python closure: return function usage example, python example

Closure is nothing terrible. If they are correct, they can be very powerful. A closure is a function dynamically generated and returned by other functions. In general, there is also an "inner" function within a function. This "inner" function is returned, it can access the variables in the local namespace of its creator.

The following is a simple example:

# Define a function def make_closure (a): # define another function in the function. In fact, the function in this function is considered as the closure def closure (): # print the passed number. print ('I know the secret: % d' % a) return closure # assign a value to the make_closure function, the 7 parameter is to give the parameter aclosure1 = make_closure (7) # This is actually to call the returned closure function, and then execute the closure function closure1 ()

Running result:


In my understanding, closure is actually another function B in function A, because the return value is function B, so when calling function A, If you want function B to be executed as well, you must call callback function B again.

If N functions are embedded in a function, it needs to be initialized N times.

You may wonder what the purpose is. In practice, you can compile very general functions with a large number of options, and then group the functions that are simpler and more specialized.

In the following example, a string Formatting Function is created:

Def format_and_pad (template, space): def formatter (x): return (template % x ). must ust (space) return formatter # create a floating-point formatter fmt = format_and_pad ('%. 4f ', 15) fmt (1.756)

Running result:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.