python——函数——高阶函数

本文深入探讨了高阶函数的概念,包括参数为函数、返回值为函数及嵌套函数三种形式,并通过具体示例展示了如何使用这些高阶函数进行数学运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高阶函数

高阶函数,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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值