python "send" 方法不会改变 "next" 的值?

python "send" method doesn't change the value of "next"?

我正在尝试生成器的发送功能,我期望发送会改变正在产生的值,所以我尝试了 ipython:

In [17]: def z(n):
    ...:     i=0
    ...:     while(i<n):
    ...:         val=yield i
    ...:         print "value is:",val
    ...:         i+=1
    ...:
In [24]: z1=z(10)
In [25]: z1.next()
Out[25]: 0

In [26]: z1.send(5) # I was expecting that after "send", output value will become "5"
value is: 5
Out[26]: 1

In [27]: z1.next()
value is: None # I was expecting that z1.next() will restart from "6" because I sent "5"
Out[27]: 2

嗯,我想我对 "send" 的真正作用有错误的理解,如何纠正它?

您产生了 i 但您没有将 yield 语句中的 return 值分配给它。如果您分配 return 值,您将看到您期望的输出:

def z(n):
    print 'Generator started'
    i=0
    while(i<n):
        val=yield i
        print "value is:",val
        if val is not None:
            i = val
        i+=1

z1=z(10)
print 'Before start'
print z1.next()
print z1.send(5)
print z1.next()

输出:

Before start
Generator started
0
value is: 5
6
value is: None
7

更新:第一次调用sendnext时,生成器从start开始执行到第一个yield语句此时值被 return 发送给调用者。这就是为什么 value is: 文本在第一次调用时看不到的原因。当第二次调用 sendnext 时,执行从 yield 恢复。如果 send 被调用,则给它的参数由 yield 语句 return 编辑,否则 yield returns None.