转载请注明出处:https://blog.csdn.net/jpch89/article/details/87036970
生成器这一块,对于next,send网上的介绍比较多,但对于throw以及close很多书上写的比较少,可能用的比较少,好在网上有很多介绍。
以下是流畅的Python对throw和close的介绍:
generator.throw(exc_type[, exc_value[, traceback]])
致使生成器在暂停的yield表达式处抛出指定的异常。如果生成器处理了抛出的异常,代码会向前执行到下一个yield表达式,而产出的值会调用generator.throw方法得到的返回值。如果生成器没有处理抛出的异常,异常会向上冒泡,传到调用方的上下文中。
generator.close()
致使生成器在暂停的yield表达式处抛出GeneratorExit异常。如果生成器没有处理这个异常,或者抛出了StopIteration异常(通常是指运行到结尾),调用方不会报错。如果收到GeneratorExit异常,生成器一定不能产出值,否则解释器会抛出RuntimeError异常。生成器抛出的其他异常会向上冒泡,传给调用方。
next就是send(None)
生成器第一次需要预激,到达第一个yield处,预激可以用next或send(None),预激将产出第一个值,并到达第一个yield处
到达yield处可以send(object)了。
In [319]: def demo():
...: for i in range(5):
...: res = yield i
...: print(res)
...:
In [320]: d = demo()
In [321]: type(d)
Out[321]: generator
In [322]: next(d)
Out[322]: 0
In [323]: d.send(‘ok‘)
ok
Out[323]: 1
In [324]: d.send(None)
None
Out[324]: 2
In [325]: next(d)
None
Out[325]: 3
In [326]: next(d)
None
Out[326]: 4
In [327]: next(d)
None
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-327-9b2daf1403f5> in <module>
----> 1 next(d)
StopIteration:
In [328]: next(d)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-328-9b2daf1403f5> in <module>
----> 1 next(d)
StopIteration:
简单的测试了next与send,接着测试throw
Python 生成器与它的 send,throw,close 方法(转帖以及记录)
原文:https://www.cnblogs.com/sidianok/p/12229822.html