高阶函数
高阶函数,higher-order function,是比普通函数更高层次的抽象,包括:
- 参数为函数
- 返回值为函数
嵌套函数
def arith(a, b, op):
def add(a, b):
print a, '+', b, '=', a + b
def sub(a, b):
print a, '-', b, '=', a - b
def mul(a, b):
print a, '*', b, '=', a * b
def div(a, b):
print a, '/', b, '=', a / b
if op == '+':
add(a, b)
elif op == '-':
sub(a, b)
elif op == '*':
mul(a, b)
elif op == '/':
div(a, b)
arith(18, 8, '+')
arith(18, 8, '-')
arith(18, 8, '*')
arith(18, 8, '/')
output:
18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2
总结:
- 函数本质是对象,无论嵌套函数还是普通函数,因此嵌套函数定义与普通函数定义无区别,都是定义函数对象
- 嵌套函数定义相当于外围函数对象内定义函数对象(嵌套函数),因此嵌套函数只对其外围函数可见
参数为函数
def add(a, b):
print a, '+', b, '=', a + b
def sub(a, b):
print a, '-', b, '=', a - b
def mul(a, b):
print a, '*', b, '=', a * b
def div(a, b):
print a, '/', b, '=', a / b
def arith(fun, a, b):
fun(a, b)
arith(add, 18, 8)
arith(sub, 18, 8)
arith(mul, 18, 8)
arith(div, 18, 8)
output:
18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2
返回值为函数
def arith(op):
def add(a, b):
print a, '+', b, '=', a + b
def sub(a, b):
print a, '-', b, '=', a - b
def mul(a, b):
print a, '*', b, '=', a * b
def div(a, b):
print a, '/', b, '=', a / b
if op == '+':
return add
elif op == '-':
return sub
elif op == '*':
return mul
elif op == '/':
return div
add = arith('+')
sub = arith('-')
mul = arith('*')
div = arith('/')
add(18, 8)
sub(18, 8)
mul(18, 8)
div(18, 8)
output:
18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2