如何解决生成器方法throw的返回值
抛出的帮助说:
buildins.generator实例的throw(...)方法 throw(typ [,val [,tb]])->在生成器中引发异常, 返回下一个产生的值或提高StopIteration
“返回下一个产生的值”,这是我的问题!
让我们看看这个例子:
def gen():
counter = 1
while True:
try:
yield counter
counter += 1
except Exception as e:
print("Exception and tpye: ",e,type(e))
x = gen()
print("Result of first next call: ",next(x))
res = x.throw(ValueError("Whatever!"))
print("result of throw call: ",res)
print("Result of first next call: ",next(x))
输出看起来像这样:
Result of first next call: 1
Exception and tpye: Whatever! <class 'ValueError'>
result of throw call: 1
Result of first next call: 2
throw的返回值不是2而是1?帮助文件显示“返回NEXT产生值2”而不是“再次返回先前产生的值”
恐怕我完全错了吗?
解决方法
使用gen.throw(...)
时,yield
语句会引发异常。
在捕获它的同时,不执行以下计数器递增。您可以将其移至finally:
子句中,以确保无论如何您总是增加counter
:
def gen():
counter = 1
while True:
try:
yield counter
except Exception as e:
print("Exception and type: ",e,type(e))
finally:
counter += 1
,
将计数器放在收益率之前:
counter += 1
yield counter
否则,第一个收益将是counter==1
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。