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:
PRINTF125
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)
Summarize:
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?