gpt4 book ai didi

python - UnboundLocalError : local variable 'e' referenced before assignment

转载 作者:行者123 更新时间:2023-12-03 15:48:24 25 4
gpt4 key购买 nike

为什么这段代码不起作用?

def test():   
e = None
try:
raise Exception

except Exception as e:
pass

return e

test()

我收到此错误:

UnboundLocalError:分配前引用的局部变量“e”

最佳答案

当异常被捕获并绑定(bind)到一个名称时,该名称在 try 之后被清除。陈述。来自 documentation of the try statement :

except E as N:
foo

行为相同
except E as N:
try:
foo
finally:
del N

因此,如果捕获到异常, e不再存在一次 return e已达到。这样做是为了打破堆栈帧(包含对 e 的引用)和由 e 引用的回溯之间的引用循环。 (其中包含对堆栈帧的引用)。

关于python - UnboundLocalError : local variable 'e' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62250236/

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