python——函数——高阶函数

来源:互联网 发布:python 安装xpath 编辑:程序博客网 时间:2024/06/04 23:18

高阶函数

高阶函数,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 = 2618 - 8 = 1018 * 8 = 14418 / 8 = 2
总结:
  • 函数本质是对象,无论嵌套函数还是普通函数,因此嵌套函数定义与普通函数定义无区别,都是定义函数对象
  • 嵌套函数定义相当于外围函数对象内定义函数对象(嵌套函数),因此嵌套函数只对其外围函数可见

参数为函数

def add(a, b):    print a, '+', b, '=', a + bdef sub(a, b):    print a, '-', b, '=', a - bdef mul(a, b):    print a, '*', b, '=', a * bdef div(a, b):    print a, '/', b, '=', a / bdef 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 = 2618 - 8 = 1018 * 8 = 14418 / 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 divadd = arith('+')sub = arith('-')mul = arith('*')div = arith('/')add(18, 8)sub(18, 8)mul(18, 8)div(18, 8)
output:
18 + 8 = 2618 - 8 = 1018 * 8 = 14418 / 8 = 2
0 0
原创粉丝点击