2014-11-23 96 views
4

目前我正在學習Python的龍捲風,我發現一個有趣的高清here,示例代碼都按python def有可能包含「yield」和「return」兩個參數嗎?

@gen.coroutine 
def fetch_coroutine(url): 
    http_client = AsyncHTTPClient() 
    response = yield http_client.fetch(url) 
    return response.bodyere 

正如你所看到的高清功能包括產量和回報......那麼,是不是按照python規則?我們如何使用這種def?誰能給我一些樣本將被非常感謝......

+0

當你嘗試時發生了什麼? – 2014-11-23 13:12:34

+0

我想這是爲python> = 3.3 – 2014-11-23 13:12:36

+0

我試過了,它總是給我例外'返回'與生成器內的參數 – liuzhidong 2014-11-23 13:18:39

回答

3
>>> def f(): 
...  yield 1 
...  return 2 
... 
>>> g = f() 
>>> next(g) 
1 
>>> next(g) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration: 2 

return在發電機停止其執行和結束通過提高StopIteration迭代。顯然,在return中給出一個值只是將它作爲參數傳遞給StopIteration異常。

這是pointed out在評論中傳遞像這樣的值是隻允許自Python 3.3以來。

在正常迭代中不能看到該值(即for x in f())。

似乎Tornado通過使用next迭代並捕獲該異常來做一些特殊的事情。協程是一個複雜的主題。這可能是協程的「結果」,其中的yield只是暫停執行和交換數據。

2

不適用於Python 2.在Python 2中,包含「yield」的函數可以具有沒有值的裸「返回」,但不允許返回值。龍捲風解決這個問題:你可以得到再提升gen.Return(值):

@gen.coroutine 
def fetch_coroutine(url): 
    http_client = AsyncHTTPClient() 
    response = yield http_client.fetch(url) 
    raise gen.Return(response.body) 

在Python 3.3及更高版本,包含一個函數「產量」也可以返回一個值:

@gen.coroutine 
def fetch_coroutine(url): 
    http_client = AsyncHTTPClient() 
    response = yield http_client.fetch(url) 
    return response.body 

Python 3.3獲得了從PEP 380中的發生器返回值以及新語句「yield from」的能力。

相關問題