yield 函数

来源:互联网 发布:caxa数控车床编程软件 编辑:程序博客网 时间:2024/06/02 03:35
1.调用 yield 
注意: generator 中 的 next() 方法 在 python 3.x 中改成了 generator.__next__()
def gen():            print('enter')            yield 1            print('next')            yield 2            print('next end')print('begin...')gen()# 直接调用,发现打印没有执行(与平常的函数不同)# 从容器里拿到 iterator 的时候它还什么也不是,处在容器入口处,对于数组来说就是下标为-1的地方,对于函数来说就是函数入口嘛事没干,但是万事俱备就欠 next 。print('end...')for i in gen():    print('...%d...' % i)c = gen()print(c.__next__()) # 调用第一个 yieldprint(c.send(None)) # 调用第二个 yield, 这里 next() 与 send(None) 是同样效果的print(c.__next__())
2.经过 close() 跟 throw() 方法来产生一个 GeneratorExit
def close(self):
            try:
                self.throw(GeneratorExit)
            except (GeneratorExit, StopIteration):
                pass
            else:
                raise RuntimeError("generator ignored GeneratorExit")  # Other exceptions are not caught
c = gen()print(c.__next__()) # 调用第一个 yieldc.close()print(c.__next__()) # 调用第二个 yield 出错了,抛出 StopIteration 的异常, 因为前面的 close 已经关闭它了



0 0
原创粉丝点击