[Python] What the hell is a closure?

Source: Internet
Author: User

These are the things I learned in the Python class network, the great god of Liao Xuefeng. Share them in the form of notes you write.

Take a look at the code first:

1 defF1 (x):2     returnx*x3     4 defNew_fn (f):5     deffn (j):6         Print 'Print'+f.__name__7         returnF (j)8     returnfn9     TenG1 =new_fn (F1) One PrintG1 (5)

Operation Result:


1. Why are closures used?

If you do not modify the F1 function, the name of the output F1 function

2. What the hell is a closure?

The NEW_FN () function passes in a parameter F (f is a function), and NEW_FN () has an FN () function, which is where the parameter function is added.

The FN () function can use the parameter F that is received by the NEW_FN () function.

3. When instantiating the G1 is actually the function fn () (inaccurate but good understanding), the incoming parameter F1 is the function to increase the function.

It is important to note that G1 is a function name, plus () can be used as a function. (because FN returns a function object)


A. Closures are meant to keep the code inside the original function, and to give it a means of adding ' sexual function '.

B. Through the outer layer of the function of the parameters passed, so that the most inner function can directly call the outer function of all parameters, so as to implement the code of the original function, add new features of the method.

Finally, in Python, decorators are the best embodiment:

Look at the code:

Implements how long the output incoming parameters are running, and outputs the time units that are passed in parameters.

Import TimedefPerformance (unit):defPerformance_decorator (f):defp (x): T1=Time.time () R=f (x) T2=time.time ()Print 'Call %s () in%f%s'% (f.__name__, T2-T1, Unit)returnRreturnPreturnPerformance_decorator@performance ('Ms')deffactorial (n):returnReduceLambdaX,y:x*y, Range (1, n+1))PrintFactorial (10)

[Python] What the hell is a closure?

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.