码迷,mamicode.com
首页 > 编程语言 > 详细

Python Generator 运行细节验证

时间:2015-05-24 01:19:33      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

今天来__next__和send, 改天来throw和close

class A:
    def __setattr__(self, key, val):
        print(‘set %s to %s‘%(key, val))
        self.__dict__[key] = val

def G():
    e = A()
    i = 0
    while 1:
        e.x = (yield i)
        print(‘    e.x is %s‘%e.x)
        i+=1

def p(s):
    print(‘        out put: %s\n‘% s)
    
g = G()

p(next(g))
p(next(g))
p(g.send(‘x1‘))
p(g.send(‘x2‘))
p(next(g))

结果:

>>> 
        out put: 0

set x to None
    e.x is None
        out put: 1

set x to x1
    e.x is x1
        out put: 2

set x to x2
    e.x is x2
        out put: 3

set x to None
    e.x is None
        out put: 4

 

Python Generator 运行细节验证

标签:

原文地址:http://www.cnblogs.com/xiangnan/p/4525259.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!