gpt4 book ai didi

python - Python "yield"的行为

转载 作者:太空狗 更新时间:2023-10-29 18:13:56 25 4
gpt4 key购买 nike

我正在阅读有关 python 中的 yield 关键字的内容,并试图了解如何运行此示例:

def countfrom(n):
while True:
print "before yield"
yield n
n += 1
print "after yield"

for i in countfrom(10):
print "enter for loop"
if i <= 20:
print i
else:
break

输出是:

before yield
enter for loop
10
after yield
before yield
enter for loop
11
after yield
before yield
enter for loop
12
after yield
before yield
enter for loop
13
after yield
before yield
enter for loop
14
after yield
before yield
enter for loop
15
after yield
before yield
enter for loop
16
after yield
before yield
enter for loop
17
after yield
before yield
enter for loop
18
after yield
before yield
enter for loop
19
after yield
before yield
enter for loop
20
after yield
before yield
enter for loop

看起来 yield 将返回指定的值,并将继续运行函数直到结束(可能在并行线程中)。我的理解正确吗?

如果您能在不提及“生成器”的情况下回答这个问题,我将不胜感激,因为我试图一次理解一个。

最佳答案

您可以将其视为 yield 的函数在遇到 yield 时简单地“暂停”。下次您调用它时,它将在 yield 之后恢复,保持它离开时的状态

关于python - Python "yield"的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7362900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com