简体   繁体   English

Python生成器 - float((yield))?

[英]Python generators - float( ( yield ) )?

I am reading the following tutorial about generators in Python http://excess.org/article/2013/02/itergen2/ 我正在阅读以下有关Python生成器的教程http://excess.org/article/2013/02/itergen2/

It contains the following code: 它包含以下代码:

def running_avg():
    "coroutine that accepts numbers and yields their running average"
    total = float((yield))
    count = 1
    while True:
        i = yield total / count
        count += 1
        total += i

I don't understand the meaning of float((yield)) . 我不明白float((yield))的含义。 I thought yield was used to "return" a value from a generator. 我认为yield用于从发生器“返回”一个值。 Is this a different use of yield ? 这是对yield的不同用途吗?

Its an extended yield syntax for coroutines 它是协同程序的扩展yield语法

Read this: http://www.python.org/dev/peps/pep-0342/ 阅读本文: http//www.python.org/dev/peps/pep-0342/

Yes, yield can also recieve , by sending to the generator: 是的,通过发送到发电机也可以收到 yield

>>> avg_gen = running_avg()
>>> next(avg_gen)  # prime the generator
>>> avg_gen.send(1.0)
1.0
>>> print avg_gen.send(2.0)
1.5

Any value passed to the generator.send() method is returned by the yield expression. yield表达式返回传递给generator.send()方法的任何值。 See the yield expressions documentation. 请参阅yield表达式文档。

yield was made an expression in Python 2.5; yield在Python 2.5中yield了表达; before it was just a statement and only produced values for the generator. 之前它只是一个声明,只生成了发电机的值。 By making yield an expression and adding .send() (and other methods to send exceptions as well) generators are now usable as simple coroutines ; 通过使yield成为表达式并添加.send() (以及其他方法来发送异常),生成器现在可以用作简单的协同程序 ; see PEP 342 for the initial motivations for this change. 请参阅PEP 342了解此变更的初步动机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM