- 1. 回调函数
- 2. 闭包函数
- 3. 匿名函数
- 4. 迭代器
定义:函数中的一个参数是函数,并且在函数中调用了传递进来的函数
def fun(x,y,f):
'''
x,y int
f function
'''
print(f(x,y))
fun(2,3,pow)
2. 闭包函数
定义:在外函数中定义并返回的函数
特点:
① 在外函数中定义并返回的函数
② 在外函数中定义了局部变量,并在内函数中使用了局部变量
③ 保护了函数的变量不受外界影响,但又能不影响使用
def person(): money = 0 # 定义的局部变量 def work(): nonlocal money money +=100 print(money) return work res = person() # return function work() res() # use function work()3. 匿名函数
3.1 定义: lambda表达式,不是代码块,是一行代码的函数
3.2 应用:
① 简单运算
格式: lambda 参数列表:表达式
# 函数原型
def plus(x,y):
return x+y
print(plus(2,3))
# 匿名函数
res = lambda x,y:x+y
res()
② 分支结构运算
格式: lambda 参数列表:真区间 if 判断 else 假区间
def fun(sex):
if sex == '男':
return 'man'
else:
return 'woman'
print(fun('男'))
res = lambda sex:'man' if sex='男' else 'woman'
4. 迭代器
4.1 可迭代对象和迭代器:
(1)可迭代对象(str,list,tuple,dict,set,range)
(2)迭代器:是访问集合元素的一种方式,只能从前往后逐个遍历,不能后退
note: 迭代器一定是可迭代对象,可迭代对象不一定是迭代器
4.2 迭代器转化和取值的方式:
(1)迭代器转换:
iter():将可迭代对象转化为迭代器
(2)迭代器取值的三种方式:
① next():迭代器的下一个数字
② list():取出迭代器中的所有数据
③ for
note: 三种方式取出一个少一个,直到迭代器为空
arr = [1,'Bob',3,4] # 可迭代对象 # 1. iter()迭代器转化 res = iter(arr) # 迭代器 # 2. next()调用 r = next(res) r = next(res) print(r) # 3. list()调用 r = list(res) print(r)
4.3 检测迭代器和可迭代对象:
from collections.abs import Iterator,Iterable # 1. type() # 2. isinstance() print(isinstance(arr,list)) print(isinstance(res,Iterator))



