Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in 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?
我认为最好避免这种情况。写得越来越清楚:
'a' in vars() or 'a' in globals()
如果你想学究,你也可以检查内置
'a' in vars(__builtins__)
相关问题 更多 >
编程相关推荐