python中发生异常时的变量范围 [英] Variable scope in case of an exception in python
本文介绍了python中发生异常时的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
while True:
try:
2/0
except Exception as e:
break
print e
给出:整数除法或取模取零
Gives: integer division or modulo by zero
我认为 e
的范围在 while
块之内,并且在外部 print
语句。我错过了什么?
I thought scope of e
is within the while
block and it will not be accessible in the outside print
statement. What did I miss ?
推荐答案
简单:而
不会创建Python中的作用域。 Python仅具有以下作用域:
Simple: while
does not create a scope in Python. Python has only the following scopes:
- 函数作用域(可能包括闭合变量)
- 类作用域(仅在定义类时)
- 全局(模块)作用域
- 理解/生成器表达式作用域
- function scope (may include closure variables)
- class scope (only while the class is being defined)
- global (module) scope
- comprehension/generator expression scope
因此,当您离开 while
循环时, e
,
So when you leave the while
loop, e
, being a local variable (if the loop is in a function) or a global variable (if not), is still available.
tl; dr:Python不是C。仍然可以使用局部变量(如果循环在函数中)或全局变量(如果没有)。
tl;dr: Python is not C.
这篇关于python中发生异常时的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文