标签:cep col close class error nbsp span throw gen
生成器除了前面提到的send方法传参之外,还有两个比较重要的方法
close() : 关闭生成器. 关闭生成器之后,如果后面还想从生成器中值 ,会报错
throw() : 传个异常到生成器内部
def gen_func(): yield 1 yield 2 yield 3 if __name__ == ‘__main__‘: # 生成一个生成器对象 gen = gen_func() print(next(gen)) # 1 gen.close() print(next(gen)) # close gen 之后 ,报StopIteration错
def gen_func(): yield 1 yield 2 yield 3 if __name__ == ‘__main__‘: # 生成一个生成器对象 gen = gen_func() print(next(gen)) # 1 gen.throw(Exception, ‘error....‘) # 抛个异常 print(next(gen)) # 不会执行,
def gen_func(): try: yield 1 except: pass yield 2 yield 3 if __name__ == ‘__main__‘: # 生成一个生成器对象 gen = gen_func() print(next(gen)) # 1 gen.throw(Exception, ‘error....‘) # 抛个异常 print(next(gen)) # 3 , 生成器中将异常捕获 , 这里正常执行
标签:cep col close class error nbsp span throw gen
原文地址:https://www.cnblogs.com/z-qinfeng/p/12094281.html