洛阳铲的日志

2010年10月13日

python的生成器

Filed under: Python — 标签:, , — HackGou @ 17:58

这个列子来自yield的手册页:

def echo(value=None):
#print "Execution starts when 'next()' is called for the first time."
try:
i = 1
while True:
try:
a = (yield value+i)
i=i+1
print "The value of yield:",a
except GeneratorExit:
# never catch GeneratorExit
raise
except Exception, e:
a = e
finally:
print "Don't forget to clean up when 'close()' is called."
print "generator starting"
generator = echo(1)
print "generator retured"
print
print "1st time next starting:"
t=generator.next()
print "return of the 1st next:",t
print "1st time next end "
print
print "2nd time next starting:"
t=generator.next()
print "return of the 2st next:", t
print "2nd time next end"
print
print "3rd time next starting:"
t=generator.send("My Value")
print "return of the send:",t
print "3rd time next end"
print
generator.throw(TypeError, "spam")
print
generator.close()
 

执行结果:

generator starting
generator retured
1st time next starting:
return of the 1st next: 2
1st time next end
2nd time next starting:
The value of yield: None
return of the 2st next: 3
2nd time next end
3rd time next starting:
The value of yield: My Value
return of the send: 4
3rd time next end
            
Don't forget to clean up when 'close()' is called.

换句话说,结合上面上面的例子,可以知道yield会出现这些结果:

1. 同时next()和send(None)是等价的。

2. 而send(value), a=yield a+i两条语句, 会让value的值成为yield的返回值,即a=value,同时a+i作为send(value)的返回值。

没错: a=value; 而 send()的值为: a+i.

3. next()返回yield之后的值,即: next()返回value+i

参考资料:

[1]: 奇妙的流控制 Python中的迭代器与生成器: http://developer.51cto.com/art/201007/212841.htm

没有评论 »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress