我试图了解 python 生成器的一些微妙细节。我编写的一个测试程序,看看我是否可以向/从同一个生成器交替发送和读取值,如下所示:
def injector():
while True:
try:
print 'a'
v = yield
print 'b', v
yield v
print 'c'
except GeneratorExit:
print 'exit'
break
g = injector()
print 'send none'
g.send(None)
print 'send 2'
g.send(2)
print 'receiving'
v = g.next()
print 'received', v
g.close()
该程序的预期输出是:
send none
a
send 2
b 2
receiving
received 2
c
a
exit
我得到的输出是:
send none
a
send 2
b 2
receiving
c
a
received None
exit
现在,显然,问题是为什么我会得到上述输出?我不了解发电机的工作原理是什么?