收益和收益在同一个函数中 [英] Return and yield in the same function

查看:90
本文介绍了收益和收益在同一个函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在Python的同一函数中使用yield和return时,到底发生了什么?

What exactly happens, when yield and return are used in the same function in Python, like this?

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

它仍然是发电机吗?

推荐答案

是的,它仍然是生成器. return(几乎)等同于提高StopIteration.

Yes, it' still a generator. The return is (almost) equivalent to raising StopIteration.

PEP 255 阐明了这一点:

规格:返回

生成器函数还可以包含以下形式的返回语句:

Specification: Return

A generator function can also contain return statements of the form:

"return"

请注意,不允许在其中的return语句上使用expression_list 发电机的主体(当然,它们可能会出现在发电机中 非生成器函数的主体嵌套在生成器中.

Note that an expression_list is not allowed on return statements in the body of a generator (although, of course, they may appear in the bodies of non-generator functions nested within the generator).

遇到return语句时,控制将按以下方式继续进行: 函数返回,执行适当的finally子句(如果有) 存在).然后引发StopIteration异常,表明 迭代器已耗尽.如果发生以下情况,也会引发StopIteration异常 控制从生成器的末端流出而没有明确的返回.

When a return statement is encountered, control proceeds as in any function return, executing the appropriate finally clauses (if any exist). Then a StopIteration exception is raised, signalling that the iterator is exhausted. A StopIteration exception is also raised if control flows off the end of the generator without an explict return.

请注意,return的意思是我已经完成了,没什么有趣的事了. return",适用于生成器函数和非生成器函数.

Note that return means "I'm done, and have nothing interesting to return", for both generator functions and non-generator functions.

请注意,返回并不总是等同于提高StopIteration: 不同之处在于如何封装try/except构造 治疗.例如,

Note that return isn't always equivalent to raising StopIteration: the difference lies in how enclosing try/except constructs are treated. For example,

>>> def f1():
...     try:
...         return
...     except:
...        yield 1
>>> print list(f1())
[]

因为与任何函数一样,return只是退出,但是

because, as in any function, return simply exits, but

>>> def f2():
...     try:
...         raise StopIteration
...     except:
...         yield 42
>>> print list(f2())
[42]

因为StopIteration被一个裸露的"except"捕获,

because StopIteration is captured by a bare "except", as is any exception.

这篇关于收益和收益在同一个函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆