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
>>>