繁体   English   中英

变量是否已定义或会引发异常

[英]Is the variable defined or will it raise an exception

阅读这本书,并试图理解一些东西。 在这个 try and except 子句中,我被告知会引发异常,因为变量 C 未定义,但看起来变量已定义。 是因为 try/except 子句吗? 似乎 C 的价值是“我永远不会被定义”。

try:
    10 / 0
    c = "I will never get defined."
except ZeroDivisionError:
    print(c)

永远不会定义c的原因是因为10/0会引发错误。 出现错误时,try 块无法继续,将跳转到 except 块。 最后, c还没有被定义。

这是一步一步发生的事情:

  • Python进入try.. except
  • 10 / 0被执行并引发ZeroDivisionError异常
  • Python 跳转到块的except部分,跳过c =指令
  • print(c)被执行,但由于c的定义被跳过,引发了一个新的异常

在模块级别,变量在第一次赋值之前不存在。

c = "I will never get defined."

在模块的命名空间中创建变量“c”并分配字符串。 在分配之前,模块命名空间中根本不存在“c”。 如果在错误之前打印命名空间变量,则没有“c”。 我添加了“foo”来演示已分配的变量。

try:
    foo = "I am defined!"
    print("Existing variables:", sorted(globals().keys()))
    10 / 0
    c = "I will never get defined."
except ZeroDivisionError:
    print(c)

Output

Existing variables: ['__annotations__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__',
'__spec__', 'foo']

Traceback (most recent call last):
  File "m.py", line 4, in <module>
    10 / 0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "m.py", line 7, in <module>
    print(c)
NameError: name 'c' is not defined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM