小编典典

确定是否在Python中定义了变量

python

您如何知道在运行时是否已在代码的特定位置设置了变量?这并不总是很明显,因为(1)可以有条件地设置变量,而(2)可以有条件地删除变量。我正在寻找类似defined()Perl或isset()PHP或defined?Ruby中的东西。

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

阅读 208

收藏
2020-12-20

共1个答案

小编典典

try:
thevariable
except NameError:
print(“well, it WASN’T defined after all!”)
else:
print(“sure, it was defined.”)

2020-12-20