官方文档对generator.send(value)的介绍。
generator.send(value)
Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.
第一次调用时,必须send(None)
value会作为yield的返回值
next方法相当于传入的value值为None
代码示例
生成器test_send()每次yield出(n+1)个temp,主函数中示例send使用及其返回值,结果如下!
每次send的值会作为temp的值,但是这个值函数并不保存,我在主函数中为send传入。send函数的返回值是在这次传入value的情况下,下一次yield会返回的值,但执行次数并不会受影响。能作为协程的实现方法之一,就是用的生成器的send()方法。