2016-06-12 52 views
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 
>>> 

回答

2

在交互模式下,巨蟒自動打印,其值比None其他東西的任何表達式語句的repr 。這不包括內部函數和類表達式語句,但它包含在循環表達式語句,比如這一個:

>>> for n in c: 
...  print(n) 
...  if n == 5: 
...   c.send(3) # <- right here 

這也正是3來自於交互模式。就我個人而言,我從來沒有遇到這種行爲是可取的情況。

相關問題