<分区>
为什么删除了except
语句中使用的变量?我的意思是:
x = 0
try:
x = 5/0
except ZeroDivisionError as x:
pass
print(x)
我收到 NameError: name 'x' is not defined
为什么会这样?它不能像使用 def
或理解一样工作吗?如果在封闭函数(或模块)中有一个与变量同名的变量,它只是被隐藏而不是被删除?
标签 python python-3.x
<分区>
为什么删除了except
语句中使用的变量?我的意思是:
x = 0
try:
x = 5/0
except ZeroDivisionError as x:
pass
print(x)
我收到 NameError: name 'x' is not defined
为什么会这样?它不能像使用 def
或理解一样工作吗?如果在封闭函数(或模块)中有一个与变量同名的变量,它只是被隐藏而不是被删除?
最佳答案
这在 the documentation 中有解释([ ] 大括号中的部分由我添加):
When an exception has been assigned using
as target
[i.e.as x
in your case], it is cleared at the end of the except clause. This is as if
except E as N:
foo
was translated to:
except E as N:
try:
foo
finally:
del N
This means the exception must be assigned to a different name to be able to refer to it [i.e. this name,
x
in your case] after the except clause.
也说明了原因:
Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.
关于python - 为什么删除 except 中使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25415541/