【问题标题】:What is the result of a yield expression in Python?Python中的yield表达式的结果是什么?
【发布时间】:2012-05-28 13:20:33
【问题描述】:

我知道yield把一个函数变成了一个生成器,但是yield表达式本身的返回值是多少呢?例如:

def whizbang(): 
    for i in range(10): 
        x = yield i

这个函数执行时变量x的值是多少?

我已阅读 Python 文档:http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt,似乎没有提及 yield 表达式本身的值。

【问题讨论】:

  • 当然,实验结果是它总是返回“None”,但我只是想确认一下。
  • 您的链接指向yield 的文档作为声明,但您在示例代码中使用了yield expression。

标签: python generator yield


【解决方案1】:

您还可以将send 值传递给生成器。如果未发送任何值,则x 为None,否则x 采用发送的值。这是一些信息:http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features

>>> def whizbang():
        for i in range(10):
            x = yield i
            print 'got sent:', x


>>> i = whizbang()
>>> next(i)
0
>>> next(i)
got sent: None
1
>>> i.send("hi")
got sent: hi
2

【讨论】:

  • 哇。为什么在产量文档中没有提到这一点完全超出了我的范围。我在哪里提交文档错误?
  • @slacy,嗯?它在yield 的文档中提到。
  • @slacy,虽然我承认环顾四周后,从目录中很难找到。
  • 这是一个文档错误吗?在docs.python.org/reference/expressions.html#yield-expressions,第二段以The value of the yield expression after resuming depends on the method which resumed the execution. 结尾,然后是next() 的方法定义When a generator function is resumed with a next() method, the current yield expression always evaluates to None. 下一个列出的方法是send():The value argument becomes the result of the current yield expression. 就在那里。
  • 有趣的是,你必须在send() 之前至少调用一次next(),否则你会得到TypeError: can't send non-None value to a just-started generator
猜你喜欢
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2016-11-04
  • 2019-02-14
  • 1970-01-01
相关资源
最近更新 更多