简体   繁体   English

Python 发电机产量行为

[英]Python generator yield behaviour

So I have the following generator function :所以我有以下生成器 function

def gen(n=5):
    for i in range(n):
        n = yield n

for i in gen(3):
    print(i)

The result:结果:

3
None
None

I understand the first result of yield is 3. Because I assigned 3 to function argument n .我知道 yield 的第一个结果是 3。因为我将 3 分配给 function 参数n But where are the None in the second and third yield coming from?但是第二个和第三个 yield 中的None是从哪里来的呢? Is it because in the for-loop, yield n returns None and this None is assigned to n in this line: n = yield n ?是因为在 for 循环中, yield n返回None并且在这一行中将这个None分配给nn = yield n

This is explained in the documentation of yield expressions , especially this part:这在yield expressions 的文档中有解释,尤其是这一部分:

The value of the yield expression after resuming depends on the method which resumed the execution.恢复后 yield 表达式的值取决于恢复执行的方法。 If next () is used (typically via either a for or the next() builtin) then the result is None.如果使用next ()(通常通过 for 或 next() 内置函数),则结果为 None。 Otherwise, if send() is used, then the result will be the value passed in to that method.否则,如果使用 send(),则结果将是传递给该方法的值。

As you use a for loop, n just gets None as a value when resuming after the first yield.当您使用for循环时, n在第一次 yield 后恢复时仅获取None作为值。 So, from now on, n is None , and this is what will be yielded the last two times.所以,从现在开始, nNone ,这就是最后两次产生的结果。

It seems to me that you answered your own question:在我看来,你回答了你自己的问题:

because in the for-loop, yield n returns None and None is assigned to n in this line: n = yield n因为在 for 循环中,yield n 返回 None 并且在这一行中 None 被分配给 n:n = yield n

You can read more at this answer .您可以在此答案中阅读更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM