Higher-order functions can return a function as a result value
Examples Show
The General quadrature function is
Vim day5-6.py
#!/usr/bin/python#-*-coding:utf-8-*-def Product (*arg): #定义求积函数 a = 1 #初始值 for i in ARG: # Iteration Loop Pass-through list a = a * I return a #返回值f = Product (1,2,3,4) print F
Running Results 24
If you don't need an immediate operation but want to do it in a later program, you can return the function without returning the result.
Vim day5-7.py
#!/usr/bin/python#-*-coding:utf-8-*-def lazy_product (*arg): def product (): a = 1 for i in arg: a = a * I return a return PRODUCTF = lazy_product (1,2,3,4) print F
Execution results
It can be seen that the return is a function body that is not executed, and the value returned each time the run is not the same even if the arguments are passed each time
Modify the code and add a line last
Print F ()
Add the () function to execute
This program structure becomes a closed packet
In order to better understand the function returned by the function body only when the call will be executed, in the view of an example
Vim day5-8.py
#!/usr/bin/python#-*-coding:utf-8-*-def count (): fs = [] for I in range (1, 4): def f (): return i*i Fs.append (f) return FSF1, F2, F3 = count () print F1 (), F2 (), F3 ()
What will the output be?
The first step is to analyze the function execution process
1,def count (): puts the function count into memory
2,f1, F2, F3 = count () Call function to return the list of functions generated to F1,F2,F3
The Count function executes a loop and returns the function body generated by the loop
3, execute F1,F2,F3
Some people think the return should be 1,4,9 actually return is 9,9,9
The reason for this is that the variable i is referenced in the function but not executed immediately, knowing that the call is executed when the value of I has changed to 3.
In order to better see the implementation process, modify the code, each step of the execution results output
Vim day5-9.py
#!/usr/bin/python#-*-coding:utf-8-*-def count (): fs = [] for I in range (1,4): def f (): return i*i Fs.append (f) print Fs,i,fs[i-1] () #输出每一次循环时候得到的函数体f, the value of I (All-in-one) and the result of executing this function print fs,i # The FS list that is obtained after three cycles is completed return FS #把列表作为函数的返回值, the list content is the function body F1,F2,F3 = count () #调用count函数把结果返回给f1, F2,f3print F1, F2,f3 #查看f1, f2,f3 gets the function body print F1 (), F2 (), F3 () #执行查看结果
Execution results
The output of the first three rows of the execution three cycles to get the value of FS and I and the value of I*i, the fourth line is the end of the loop to get the FS list and I the value of the fifth line is the Count function returned by the list fs assignment to F1,F2,F3
Line six is the result of the output at the time of execution, because the value of I is already 3, so the result is 9,9,9
The return function of Python