Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?确定是否变量在Python
定义你怎么知道一个变量是否已经被设置为在运行时代码一个特别的地方?这并不总是显而易见的,因为(1)变量可以被有条件地设置,并且(2)变量可以被有条件地删除。我正在寻找Perl中的defined()
或PHP中的isset()
或Ruby中的defined?
。
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
Duplicates:http://stackoverflow.com/questions/843277/python-checking-variable-existing,http://stackoverflow.com/questions/750298/easy-way-to-check-that-variable-is -python -defined, – carl 2009-10-20 06:50:58
请请,请不要“有条件地”设置一个变量。这只是可怕的,可怕的设计。始终,始终提供所有逻辑路径。请不要继续这样做。 – 2009-10-20 10:35:38
+1 S.Lott anwser。事实上,有办法做到这一点并不意味着你应该在一个新的项目中使用它。 – 2010-03-31 13:48:06