小编典典

确定变量是否在Python中定义

all

您如何知道变量是否已在运行时代码中的特定位置设置?这并不总是很明显,因为(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?

阅读 89

收藏
2022-03-14

共1个答案

小编典典

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

2022-03-14