我无法理解send方法。我知道它是用来操作发电机的。但是
语法如下:generator.send(value)。
我不知怎么搞不懂为什么值应该成为当前yield表达式的结果。我准备了一个例子:def gen():
for i in range(10):
X = yield i
if X == 'stop':
break
print("Inside the function " + str(X))
m = gen()
print("1 Outside the function " + str(next(m)) + '\n')
print("2 Outside the function " + str(next(m)) + '\n')
print("3 Outside the function " + str(next(m)) + '\n')
print("4 Outside the function " + str(next(m)) + '\n')
print('\n')
print("Outside the function " + str(m.send(None)) + '\n') # Start generator
print("Outside the function " + str(m.send(77)) + '\n')
print("Outside the function " + str(m.send(88)) + '\n')
#print("Outside the function " + str(m.send('stop')) + '\n')
print("Outside the function " + str(m.send(99)) + '\n')
print("Outside the function " + str(m.send(None)) + '\n')
结果是:1 Outside the function 0
Inside the function None
2 Outside the function 1
Inside the function None
3 Outside the function 2
Inside the function None
4 Outside the function 3
Inside the function None
Outside the function 4
Inside the function 77
Outside the function 5
Inside the function 88
Outside the function 6
Inside the function 99
Outside the function 7
Inside the function None
Outside the function 8
坦白地说,这让我很吃惊。在文档中,我们可以看到当执行yield语句时,生成器的状态被冻结,并且expression_list的值返回给next的调用方。
嗯,好像没发生过。为什么我们可以在gen()内部执行if语句和print函数。
我如何理解函数内部和外部的X为什么不同?
好 啊。假设send(77)将77传输到m。好吧,yield表达式变成77。
那么什么是X = yield i?函数内部的77在外部发生时如何转换为5?
为什么第一个结果字符串没有反映生成器中发生的任何事情?
不管怎样,你能对这些send和yield语句做些评论吗?