在 Pythonreturn文档中它说:“在生成器函数中,该return语句指示生成器已完成并将导致StopIteration引发。”
在下面的示例中,如果我们finally在异常处于活动状态时在块中返回,则会抑制异常并StopIteration引发 a 。是否期望异常被抑制?有没有办法在不抑制块的情况下return从块中取出finally?
def hello(do_return):
try:
yield 2
raise ValueError
finally:
print('done')
if do_return:
return
没有调用return:
>>> h = hello(False)
>>> next(h)
Out[68]: 2
>>> next(h)
done
Traceback (most recent call last):
File "E:\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-69-31146b9ab14d>", line 1, in <module>
next(h)
File "<ipython-input-63-73a2e5a5ffe8>", line 4, in hello
raise ValueError
ValueError
打电话给return:
>>> h = hello(True)
>>> next(h)
Out[71]: 2
>>> next(h)
done
Traceback (most recent call last):
File "E:\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-72-31146b9ab14d>", line 1, in <module>
next(h)
StopIteration
largeQ
暮色呼如
随时随地看视频慕课网APP
相关分类