为什么我不能使用收益与回报? [英] Why can't I use yield with return?
问题描述
def func(alist):
if len( alist)== 1:
返回arg * 2
用于alist中的项目:
收益项目* 2
当我运行它时,出现以下错误:
SyntaxError:'return'with生成器中的参数
现在,我意识到我无法做到这一点。不过,我想知道为什么。究竟是在幕后导致Python抛出 SyntaxError
?
下一个
调用之前没有运行;生成器函数返回一个生成器迭代器,当调用 next
时运行生成器代码。因此,Python无法通过运行函数直到它遇到 yield
或产生
表示该函数是一个生成器。 I would like you to consider the following code:
def func(alist):
if len(alist) == 1:
return arg * 2
for item in alist:
yield item * 2
When I run it, I get this error:
SyntaxError: 'return' with argument inside generator
Now, I realize that I cannot do this. However, I would like to know why. What exactly is going on behind the scenes that is causing Python to throw the SyntaxError
?
Python has to decide whether a function is a generator at bytecode compilation time. This is because the semantics of generators say that none of the code in a generator function runs before the first next
call; the generator function returns a generator iterator that, when next
is called, runs the generator code. Thus, Python can't decide whether a function should be a generator or not by running it until it hits a yield
or a return
; instead, the presence of a yield
in a function signals that the function is a generator.
这篇关于为什么我不能使用收益与回报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!