???一、yield 的作用
yield 在函数中相当于 return,又不同于 return,当函数执行遇到 yield 的时候,函数会停止执行,并返回 yield 后值
???二、举个栗子,看下面这段代码
def test_demo():
for num in range(1,4):
print('starting..........')
result = yield num
print('yield num并没有赋值给result,result的值为None,result = ', result)
test_generator = test_demo()
print("这里是生成器:", test_generator)
print("生成器中第1个值:", next(test_generator))
print("生成器中第2个值:", next(test_generator))
print("生成器中第3个值:", next(test_generator))
print("执行完成")
执行结果:
这里是生成器:
starting..........
生成器中第1个值:1
yield num并没有赋值给result,result的值为None,result = None
starting..........
生成器中第2个值:2
yield num并没有赋值给result,result的值为None,result = None
starting..........
生成器中第3个值:3
执行完成
???三、执行结果截图
???四、执行过程分析
- 调用 test_generator 函数的时候,因为 test_demo 函数中有 yield 关键字,所以函数不会真的执行,而是先得到一个生成器 test_generator
- 直到调用 next(test_generator) 方法,test_demo 函数开始正式执行,开始跑 for 循环
- 当函数执行到第 15 行(result = yield num),此时 yield num 并没有赋值给 result,因此 16 行打印 result 的值永远为 None
- 继续执行 19 行到 21 行顺序执行,通过 next(test_generator)将生成器的值输出
- 如果没有继续调用 next(test_generator)整个函数执行完毕了
- 顺序执行 22 行代码
???五、注意点
可以通过 send 方法给 result 重新赋值(result.send(100))
yield 后面也可以返回多个参数,多个参数返回类型为元组(通常在 pytest 前置后置中使用)