【问题标题】:Why the yield return value is changed that way?为什么收益率返回值会这样改变?
【发布时间】:2013-07-13 07:32:26
【问题描述】:
def h():  
    print 'Wen Chuan',
    m = yield 5 # Fighting!  
    print m  
    d = yield 12  
    print 'We are together!'  
c = h()  
m = c.next() #m gets the value of yield 5
d = c.send('Fighting!') #d gets the value of yield 12
print 'We will never forget the date', m, '.', d

请检查上面的代码。 运行结果如下:

>>> ================================ RESTART ================================
>>> 
Wen Chuan Fighting!
We will never forget the date 5 . 12

而且根据我的理解,第一个yield返回值改为“Fighting!”已经,但是为什么稍后print m 仍然显示值 5?

【问题讨论】:

    标签: python generator yield


    【解决方案1】:

    不,您没有更改 yield 5 表达式使生成器生成的内容。

    .send() 将更改本地m 内部h() 将被设置的内容。

    会发生什么:

    • 您创建了一个生成器函数h(),但执行被冻结。
    • 您在生成器上调用.next()。继续执行,打印'Wen Chuan',代码运行到yield 5 表达式。 5 返回并分配给全局 m。生成器再次暂停。
    • 您致电c.send('Fighting!')。继续执行,'Fighting!' 分配给生成器函数中的局部变量 mprint m 打印它。执行yield 12,暂停生成器并将12分配给全局变量d
    • 'We will never forget the date', 5, '.', 12 已打印。

    此时生成器函数仍然暂停,并且生成器函数的最后一行永远不会执行。如果你再次调用.next(),那么'We are together!' 将被打印,生成器端和StopIteration 将被提升。

    【讨论】:

      【解决方案2】:

      m 函数内部和外部是不同的变量,不会相互影响。

      【讨论】:

        猜你喜欢
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        • 2012-09-16
        • 2016-10-04
        • 2012-09-25
        相关资源
        最近更新 更多