我正在学习协程,我发现了一个叫做“关于协程和并发的有趣课程”的pdf文件。这里有一个不可靠的例子:
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“的文件中,然后转到python外壳。
>>> 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 10...但是当我把这些语句放入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)然后..。
$ python bogus.py
Counting down from 5
5
2
1
0我得到了5210...!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
>>>发布于 2016-06-12 14:03:24
在交互模式下,Python会自动打印计算结果不是None的任何表达式语句的repr。这不包括函数和类中的表达式语句,但包括循环中的表达式语句,例如:
>>> for n in c:
... print(n)
... if n == 5:
... c.send(3) # <- right here这就是交互模式下3的来源。就我个人而言,我从来没有遇到过这种行为是可取的。
https://stackoverflow.com/questions/37771137
复制相似问题