本文翻译自:Determine if variable is defined in Python [duplicate]
Possible Duplicate: 可能重复:
Easy way to check that variable is defined in python? 在python中定义检查变量的简单方法?
How do I check if a variable exists in Python? 如何检查Python中是否存在变量?
How do you know whether a variable has been set at a particular place in the code at runtime? 您如何知道变量是否已在运行时在代码中的特定位置设置? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. 这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除。 I'm looking for something like defined() in Perl or isset() in PHP or defined? 我正在寻找像Perl中的defined()或PHP中的isset()或defined? in Ruby. 在Ruby中。
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
#1楼
参考:https://stackoom.com/question/6gIX/确定变量是否在Python中定义-重复
#2楼
try:
a # does a exist in the current namespace
except NameError:
a = 10 # nope
#3楼
try:
thevariable
except NameError:
print("well, it WASN'T defined after all!")
else:
print("sure, it was defined.")
#4楼
'a' in vars() or 'a' in globals()
如果你想变得迂腐,你也可以查看内置的'a' in vars(__builtins__)
#5楼
I think it's better to avoid the situation. 我认为最好避免这种情况。 It's cleaner and clearer to write: 写起来更清晰,更清晰:
a = None
if condition:
a = 42
#6楼
For this particular case it's better to do a = None instead of del a . 对于这种特殊情况,最好做a = None而不是del a 。 This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. 这将减少对象a引用计数(如果有的话),并且在未定义a时将不会失败。 Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. 注意, del语句不直接调用对象的析构函数,而是从变量中解除绑定。 Destructor of object is called when reference count became zero. 当引用计数变为零时,将调用对象的析构函数。
本文探讨了Python中检查变量是否已定义的方法,包括使用try-except结构捕获NameError异常,以及通过vars()和globals()函数查询变量。讨论了条件设置和删除变量的场景,并对比了Perl、PHP和Ruby中的类似功能。

被折叠的 条评论
为什么被折叠?



