Python 高阶函数、高阶内建函数及柯里化
1、高阶函数
1.1 Python 函数
- 函数在 Python 里是一等公民(First-Class Object)
- 函数也是对象,是可调用对象
- 函数可以作为普通变量,也可以作为函数的参数、返回值
1.2 高阶函数
在数学和计算机科学中,高阶函数(High-order Function)应当至少满足下面一个条件的函数:
- 接受一个或多个函数作为参数
- 输出一个函数
1.3 实现计数器的高阶函数
def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
# 基数是0,步长为2的技术器
counter1 = counter(base=0)
for i in range(3):
print(counter1(step=2))
# Out
2
4
6
1.4 注意以下两个函数的区别
1.4.1 函数内嵌套函数
# == 如果无法比较内容,就等效为 is
# 例如 函数对象 无法比较内容 就直接比较内存地址
def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
f1 = counter(5)
f2 = counter(5)
print('f1 = {}, f2 = {}'.format(f1, f2))
print('f1_id = {}, f2_id = {}'.format(id(f1), id(f2)))
print('f1() = {}, f2() = {}'.format(f1(), f2()))
print('f1()_id = {}, f2()_id = {}'.format(id(f1()), id(f2())))
print(f1 == f2)
print(f1() == f2())
f1 = <function counter.<locals>._counter at 0x00000000078B13A8>, f2 = <function counter.<locals>._counter at 0x00000000078B1558>
f1_id = 126555048, f2_id = 126555480
f1() = 6, f2() = 6
f1()_id = 8791210553808, f2()_id = 8791210553808
False
True
1.4.2 函数内部返回全局函数
# == 如果无法比较内容,就等效为 is
# 例如 函数对象 无法比较内容 就直接比较内存地址
# 全局定义的函数,也就相当于一个全局变量,不管被赋值给多少变量,其 id 都是一样的
inc_num = 100
def inc(step=1):
return inc_num+1
def counter(base=0):
print(