我正在尝试生成器的发送功能,我期待发送会改变正在收益的值,所以我尝试了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
嗯,我想我对“发送”真正做了什么,如何纠正它有错误的理解?
答案 0 :(得分:6)
您正在屈服i
,但您没有将yield
语句的返回值分配给它。如果您指定了返回值,您将看到预期的输出:
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
更新:第一次调用send
或next
时,生成器从开始执行到第一个yield
语句,此时值为返回给来电者。这就是为什么在第一次调用时看不到value is:
文本的原因。当第二次调用send
或next
时,执行将从yield
恢复。如果调用了send
,则yield
语句会返回给定的参数,否则yield
会返回None
。