![](/img/trans.png)
[英]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.