1
我正在學習協程,我找到了一個名爲「協程和併發的好奇課程」的pdf。 有片狀例如:Python,爲什麼我在使用生成器良率時在.py和shell之間得到不同的結果?
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
我已經把它在一個名爲「bogus.py」文件,然後我去了蟒蛇殼..
>>> from bogus import countdown
>>> c = countdown(5)
>>> for n in c:
... print(n)
... if n == 5:
... c.send(3)
...
Counting down from 5
5
3
2
1
0
>>>
是的,我有5 3 2 1 0 ... 但是當我把這些語句到bogus.py,我得到了不同的結果...
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
c = countdown(5)
for n in c:
print(n)
if n == 5:
c.send(3)
然後...
我得到了5 2 1 0 ...! 3在哪裏? 我很困惑,我真的不知道爲什麼... 請幫助我,對不起我的英語。
哦,我還發現,如果我在shell代碼改了一下,然後我得到:
>>> from bogus import countdown
>>> c = countdown(5)
>>> for n in c:
... print(n)
... if n == 5:
... k = c.send(3)
...
Counting down from 5
5
2
1
0
>>>