生成器函数:
1. 里面有yield
2. 生成器函数在执行的时候,实际上是创建一个生成器出来
3. 必须使用__next__()来执行一段代码,会自动地执行到下一个yield结束
4. yield也是返回的意思,可以让一个函数分段执行
5. 当后面没有yield之后,再次__next__()会报错 StopIteration
6. 还可以适用send(),往yield结束的位置向函数传值
生成器代码:
def robor_produce():
for i in range(10):
yield i
tmp = robor_produce()
while True:
try:
print(tmp.__next__())
except StopIteration:
break
打印结果:
0 1 2 3 4 5 6 7 8 9
加入 send() 往函数里传入参数,但是必须要先用__next__()
def robor_produce():
print("step 1")
#b 接收send回来的数据
a = yield "step 2"
print("a = ", a)
#c 接受send回来的数据
b = yield "step3"
print("b = ", b)
yield 'end'
tmp = robor_produce()
#必须先用__next__()
print(tmp.__next__())
while True:
try:
print(tmp.send("111"))
except StopIteration:
break
打印结果:
step 1 step 2 a = 111 step3 b = 111 end



