[英]In python def statement, Is it possible to write the for loop and return statements in one line?
[英]Is it possible that a python def contains both “yield” and “return”?
目前我正在學習python龍卷風,我在這里找到一個有趣的def,示例代碼如下
@gen.coroutine
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
return response.bodyere
如你所見,def函數包含yield和return ...那么,它是否遵循python規則? 我們怎樣才能使用這種def? 任何人給我一些樣品將非常感謝...
>>> 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
異常。
在評論中指出 ,傳遞這樣的值只能從Python 3.3開始。
在正常迭代中不能看到該值(即for x in f()
)。
看起來Tornado通過迭代使用next
並捕獲該異常來做一些特別的事情。 協同程序是一個復雜的主題。 這可能是協程的“結果”,其中的yield
只是暫停執行和交換數據。
不在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及更高版本中,包含“yield”的函數也可以返回一個值:
@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”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.