gpt4 book ai didi

python - 生成器方法 throw 的返回值

转载 作者:行者123 更新时间:2023-12-04 15:17:02 25 4
gpt4 key购买 nike

throw 的帮助说:

builtins.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吗?帮助文件说“return NEXT yielded value2”不是“return again previously yielded value”

我担心我完全错了?

最佳答案

当您使用 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

关于python - 生成器方法 throw 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com