python - 为什么删除 except 中使用的变量

标签 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/

相关文章:

python - 没有括号定义函数?

python - Pandas 除法创建额外的列和 NaN

python - 生成之前没有生成过的数字或字符串?

python - 如何在 python 3.6 中键入 hinte 高阶函数?

python-3.x - 编写删除重复元素的程序时列表索引超出范围

java - 如何使用 Socket 从 Android 向 Windows 中的 python 应用程序发送消息

python - 在 Pandas 中将所有选定值替换为 NaN

python - 如果它不是函数,则将项目添加到列表中

python - 将输出值保存在 python 列中的 txt 文件中

python-3.x - Python - 为包装函数赋予与包装函数相同的名称