官方文档对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()方法。
本文详细解析了Python中生成器的send()方法的工作原理,包括如何通过send()向生成器发送值,以及send()与yield表达式的交互方式。强调了首次调用时必须send(None),并提供了代码示例来展示send()的使用及其返回值。
695

被折叠的 条评论
为什么被折叠?



