【发布时间】:2012-09-20 04:57:05
【问题描述】:
我无法理解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 声明吗?
【问题讨论】:
标签: python python-3.x generator