python def有可能包含“yield”和“return”两个参数吗?
问题描述:
目前我正在学习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?谁能给我一些样本将被非常感谢......
答
>>> 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
只是暂停执行和交换数据。
答
不适用于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”的能力。
当你尝试时发生了什么? – 2014-11-23 13:12:34
我想这是为python> = 3.3 – 2014-11-23 13:12:36
我试过了,它总是给我例外'返回'与生成器内的参数 – liuzhidong 2014-11-23 13:18:39