这个python yield函数如何工作?

goo*_*og5 1 python yield

def func():
    output = 0
    while True:
        new = yield output
        output = new


genr = func()
print(next(genr))
print(next(genr))
print(next(genr))
Run Code Online (Sandbox Code Playgroud)

输出:

0

我的想法是:

  1. genr=func() 返回一个生成器,但实际上并没有运行它.
  2. 首先print(next(genr))从func的开始运行yield output,但尚未分配回来new,因此输出0有意义.
  3. 第二个print(next(genr))开始从分配output回来new,而下一行output = new做两个outputnew0,下一个执行yield output应该返回0,但为什么它None实际返回?

Ray*_*ger 7

一个产量语句用于像返回一个值,但它不破坏栈帧(即知道当前行,局部变量和待试陈述功能的一部分).这允许在产量之后恢复功能.

当你调用一个包含yield的函数时,它会返回一个"generator",它允许你运行代码直到yield,然后从它停止的地方恢复它.

>>> def squares(n):
        for i in range(n):
            yield i ** 2

>>> g = squares(5)             # create the generator
>>> g
<generator object squares at 0x106beef10>
>>> next(g)                    # run until the first yield
0
>>> next(g)                    # resume after the yield
1
>>> next(g)                    # resume after the yield
4
>>> next(g)                    # resume after the yield
9
>>> next(g)                    # resume after the yield
16
>>> next(g)                    # looping is terminated with a StopIteration
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    next(g)                    # looping is terminated with a StopIteration
StopIteration
Run Code Online (Sandbox Code Playgroud)

有趣的是,生成器可以使用send()方法接受值.要为这种发电机灌注泵,第一次调用应该是next().

>>> def capitalize():
        word = 'start'
        while word != 'quit':
            word = yield word.capitalize()

>>> g = capitalize()
>>> next(g)                      # run to the first yield
'Start'
>>> g.send('three')              # send in a value to be assigned to word
'Three'
>>> g.send('blind')              # send in a value to be assigned to word
'Blind'
>>> g.send('mice')               # send in a value to be assigned to word
'Mice'
>>> g.send('quit')               # send in a control value
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    g.send('quit')               # send in a control value
StopIteration
Run Code Online (Sandbox Code Playgroud)

你在你的例子中想到的是,next(g)它真的是一样的g.send(None).

以下是文档的说法:

恢复后yield表达式的值取决于恢复执行的方法.如果使用__next __()(通常通过for或next()内置),则结果为None.否则,如果使用send(),则结果将是传递给该方法的值

这是一个让所有这些都可见的会话:

>>> def show_expression():
        for i in range(5):
            word = yield 10
            print('The word is %r' % word)

>>> g = show_expression()
>>> next(g)
10
>>> g.send('blue')
The word is 'blue'
10
>>> g.send('no')
The word is 'no'
10
>>> g.send('yellow')
The word is 'yellow'
10
>>> next(g)
The word is None
10
>>> g.send('done')
The word is 'done'
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    g.send('done')
StopIteration
Run Code Online (Sandbox Code Playgroud)

希望从第一原则解释所有的奥秘:-)