当在Python函数中同时使用yield和return时,会发生什么?
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
有一个参数会发生什么吗? - zwolSyntaxError: 'return' with argument inside generator
。在Python 3.x中允许使用,但主要用于协程 - 你可以通过使用yield coroutine()
(或者根据所使用的异步框架,使用yield from coroutine()
)对其他协程进行异步调用,并且可以使用return value
从协程中返回任何想要返回的值。在Python 2.x中,你需要使用类似于raise Return(value)
的技巧来从协程中返回值。 - dano