高阶函数: 变量名可以指向函数,因此函数可以通过变量传给另一个函数。
高阶函数: 一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足一种就可以称为高阶函数。
由此可知:
- 函数可以作为被调用的对象
- 函数可以作为普通变量,也可以作为函数的参数、返回值
栗子1:
f = abs
print(f(-1))
结果为: 1
栗子2:
# 求取两个数的绝对值之和
def add(x, y, f):
return f(x)+f(y)
print(add(-4, 5, abs))
得到结果为: 9
栗子3:参数为函数
def School():
print("in the school..")
def Home(func):
func()
print("in the home..")
Home(School)
结果为:
in the school…
in the home…
栗子4:返回值为函数
def School():
print("in the school..")
def Home(func):
print("in the home..")
return func()
Home(School)
def School():
print("in the school..")
def Home(func):
print("in the home..")
return func
res = Home(School)
res()
以上两种代码结果相同,这样写只是为了更加深刻的说明以下注意点:
1.函数名代表的是该函数的内存地址;
2.函数名+括号代表的是调用该函数。
练习:
求取 根号x加根号y的和:
import math
def add(x, y, f):
return f(x) + f(y)
print(add(25, 9, math.sqrt))
得到结果为: 8
大家加油
冷笑话
一锅青蛙煮于釜,其乐融融