yield和send函数

yield作用类似于return,其本质是一个迭代器。

当程序执行到yield时,会结束本次循环,返回一个值,然后内置含有next()函数,

下次在执行时,会从yield结束的地方继续执行。

带yield的函数是一个生成器,内置next函数,当本次执行到yield结束时候,下一次next就会从本次停止的地方继续执行,

碰到yield时候,就会return生成的数。

send函数

send函数给参数赋值,其执行过程也是从上一步的yield结束的时候开始。

给出一段代码参考:

1 def foo():
2     print("starting...")
3     while True:
4         res = yield 4
5         print("res:",res)
6 g = foo()
7 print(next(g))
8 print("*"*20)
9 print(next(g))

其结果:

1 starting...
2 4
3 ********************
4 res: None
5 4

send函数:

1 def foo():
2     print("starting...")
3     while True:
4         res = yield 4
5         print("res:",res)
6 g = foo()
7 print(next(g))
8 print("*"*20)
9 print(g.send(7))

其结果:

1 starting...
2 4
3 ********************
4 res: 7
5 4
原文地址:https://www.cnblogs.com/ywheunji/p/10448395.html