Python的“收益"行为 [英] Behaviour of Python's "yield"
问题描述
我正在阅读python中的yield
关键字,并试图了解如何运行此示例:
I'm reading about the yield
keyword in python, and trying to understand running this sample:
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会返回指定的值,并将继续运行该函数直到最后(可能在并行线程中).我的理解正确吗?
It looks like the yield will return the specified value, and will continue runnning the function till the end (in a parallel thread, maybe). Is my understand correct?
如果您能在不提及发电机"的情况下回答这个问题,我将非常感激,因为我想一次理解一个人.
If you could answer this without mentioning "generators", I would be thankful, because I'm trying to understand one at a time.
推荐答案
您可以将其视为yield
遇到yield
时只是暂停"的函数.下次调用它时,它将在yield
保持其离开时的状态之后恢复.
You can think of it as if the function which yield
s simply "pauses" when it comes across the yield
. The next time you call it, it will resume after the yield
keeping the state that it was in when it left.
这篇关于Python的“收益"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!