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
- yield 函数
- yield()函数的使用
- yield函数测试
- wait()、sleep()以及yield()函数
- js yield和Generator 函数
- function* 生成器函数 迭代器 yield
- Python 生成器函数_1 (yield)
- python yield函数深入浅出理解
- C#yield return和yield break函数执行逻辑理解
- yield
- yield
- yield()
- yield
- yield
- yield
- yield
- yield
- yield
- java利用反射解析xml到实体类
- lambda 格式
- Java经典类库-Guava中的函数式编程讲解
- linux yum命令详解
- 面向对象软件工程与UML
- yield 函数
- 安装sqlyog和使用注册码
- 系统启动时,spring配置文件解析失败,报”cvc-elt.1: 找不到元素 'beans' 的声明“异常
- 正则表达式
- Altium Designer经验
- C++学习(八)——函数探幽
- DEDE时间格式汇总
- XML
- python下编译py成pyc和pyo