我不理解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
语句进行一些注释呢?