def func():
output = 0
while True:
new = yield output
output = new
genr = func()
print(next(genr))
print(next(genr))
print(next(genr))
输出:
0
None
None
我的想法是:
genr=func()
返回生成器,但实际上并不运行它。在print(next(genr))
从func的开始运行到yield output
,但是还没有分配回new
,所以输出{print(next(genr))
从将output
分配回new
开始,下一行output = new
将{yield output
应该返回0,但是为什么它返回None
?在
yield expression的结果是generator.send()函数发送的值,}。因此,
next(gen)
相当于{new
每次调用next()
时都会收到值None
。在如果您改为这样做:
您将得到以下输出:
^{pr2}$yield语句类似于return返回值,但它不会破坏堆栈帧(函数中知道当前行、局部变量和挂起的try语句的部分)。这样就可以在屈服后恢复函数。在
当您调用一个包含yield的函数时,它返回一个"generator",它允许您运行代码到一个yield,然后从它停止的地方恢复它。在
有趣的是,生成器可以使用send()方法接受值。要为这种发生器启动泵,第一个调用应该是next()。在
^{pr2}$在您的示例中,您发现}相同。在
next(g)
实际上与{以下是the docs要说的:
下面是一个让所有这些都可见的会话:
希望能解释第一原则中所有的谜团:-)
相关问题 更多 >
编程相关推荐