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
- python学习——高阶函数
- Python——高阶函数
- python——函数——高阶函数
- Python学习笔记——高阶函数
- Python高阶函数——map/reduce/filter/sorted
- 【Python】学习笔记——-5.1、高阶函数
- python学习(4)——高阶函数
- python精简笔记(四)——高阶函数
- python基础—(高阶,匿名,偏)函数 | 装饰器
- Python笔记4——函数式编程,高阶函数,闭包
- Python进阶学习笔记——函数式编程之高阶函数
- python高阶函数
- python 高阶函数
- python高阶函数
- Python高阶函数
- python 高阶函数
- python高阶函数
- Python高阶函数
- 软考学习笔记
- 跟小博老师一起学习数据库 ——索引
- 设计模式之单例模式
- C#中String类的几个方法(IndexOf、LastIndexOf、Substring)
- 简易进制转换器
- python——函数——高阶函数
- 多态中的转型
- Problem B: STL——管道一
- POJ NOI0113-03 八进制小数(Bailian2765)
- 复习2
- [Visio 2007]解决 “类图”调整宽度后,换行的文字溢出的问题(如何调整“类图”的高度?)
- AndroidStudio子类快速实现未实现的方法-快捷键
- 关于时间复杂度与空间复杂度
- C/C++ 指针笔记