一个最简单的高阶函数:编程
1 def add(x, y, f): 2 return f(x) + f(y)
add(-5, 6, abs) , abs做为参数传入 add 函数中 ,又做为参数返回
一个列表运算的例子:lst = range(5) 闭包
加法:只需 for 循环遍历 lst ,依次相加,返回 amoutapp
1 amount = 0 2 for num in lst: 3 amount = add(amount, num
1 def sum_(lst): 2 amount = 0 3 for num in lst: 4 amount = add(amount, num) 5 return amount 6 7 print sum_(lst)
1 def sum_(lst): 2 amount = 0 3 for num in lst: 4 amount = add(amount, num) 5 return amount 6 7 print sum_(lst)
乘法:初始值换成了1以及函数add换成了乘法运算符 编程语言
1 def multiply(lst): 2 product = 1 3 for num in lst: 4 product = product * num 5 return product
把这个流程抽象出来,而将加法、乘法或者其余的函数做为参数传入:ide
1 def reduce_(function, lst, initial): 2 result = initial 3 for num in lst: 4 result = function(result, num) 5 return result
如今,想要算乘积:函数式编程
1 print reduce_(lambda x, y: x * y, lst, 1)
闭包是一类特殊的函数。若是一个函数定义在另外一个函数的做用域中,而且函数中引用了外部函数的局部变量,那么这个函数就是一个闭包。函数
可变参数的求和:spa
1 def calc_sum(*args): 2 ax = 0 3 for n in args: 4 ax = ax + n 5 return ax
返回求和的函数:code
1 def lazy_sum(*args): 2 def sum(): 3 ax = 0 4 for n in args: 5 ax = ax + n 6 return ax 7 return sum
调用lazy_sum()
时,返回的并非求和结果,而是求和函数blog
1 >>> f = lazy_sum(1, 3, 5, 7, 9) 2 >>> f 3 <function sum at 0x10452f668> 4 >>> f() 5 25
在函数lazy_sum
中又定义了函数sum
,而且,内部函数sum
能够引用外部函数lazy_sum
的参数和局部变量,当lazy_sum
返回函数sum
时,相关参数和变量都保存在返回的函数中,称为闭包
须要注意的问题是,返回的函数并无马上执行,而是直到调用了 f()
才执行。咱们来看一个例子:
1 def count(): 2 fs = [] 3 for i in range(1, 4): 4 def f(): 5 return i*i 6 fs.append(f) 7 return fs 8 9 f1, f2, f3 = count()
1 >>> f1() 2 9 3 >>> f2() 4 9 5 >>> f3() 6 9
返回闭包时牢记的一点就是:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
若是必定要引用循环变量怎么办?方法是再建立一个函数
1 >>> def count(): 2 ... fs = [] 3 ... for i in range(1, 4): 4 ... def f(j): 5 ... def g(): 6 ... return j*j 7 ... return g 8 ... fs.append(f(i)) 9 ... return fs