为什么我不能使用收益与回报? [英] Why can't I use yield with return?

查看:108
本文介绍了为什么我不能使用收益与回报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def func(alist):
if len( alist)== 1:
返回arg * 2
用于alist中的项目:
收益项目* 2

当我运行它时,出现以下错误:

  SyntaxError:'return'with生成器中的参数

现在,我意识到我无法做到这一点。不过,我想知道为什么。究竟是在幕后导致Python抛出 SyntaxError

解决方案

Python必须决定函数是否是字节码编译时的生成器。这是因为生成器的语义表明生成器函数中的代码在第一个下一个调用之前没有运行;生成器函数返回一个生成器迭代器,当调用 next 时运行生成器代码。因此,Python无法通过运行函数直到它遇到 yield return 来决定函数是否应该是生成器$ C>;相反,函数中存在产生表示该函数是一个生成器。


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屋!

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