这是我编写的一个小函数,用于理解发送方法:
>>> def test():
... for x in xrange(10):
... res = yield
... yield res
>>> a = test()
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a)
>>> a.send(0)
Traceback (most recent call last):
<ipython-input-220-4abef3782000> in <module>()
StopIteration
>>> a = test()
>>> a.send(0)
Traceback (most recent call last):
<ipython-input-222-4abef3782000> in <module>()
TypeError: can't send non-None value to a just-started generator
>>> a.send(None)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)
第一次出现错误的原因是什么?
>>> a.send(0)
StopIteration
为什么第一次 send() 需要是 None?这与以下错误有关:
>>> a.send(0)
Traceback (most recent call last):
<ipython-input-222-4abef3782000> in <module>()
TypeError: can't send non-None value to a just-started generator
然后第一个发送开始发电机(我不知道为什么),我发送一个“0”,它会打印出来,但第二个“0”再次是无,然后继续使用我发送的内容(这里是0)。
>>> a.send(None)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
这个链接并没有太大帮助 Python 3: 生成器的send方法
send()
中的值将被分配给coro()
内部的变量b
,但是这个值会被丢弃,因为从b = yield a
这一行到协程结束时,变量b
没有被用于任何操作。 - Augusto Hackb
将包含值the second value sent
,如果您有第三个yield
,它将接收下一个值send()
,以此类推。您可以自行处理发送的值,我只是想说您不必使用该对象。 - Augusto Hack