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

发布于 2021-01-29 19:36:41

您如何知道在运行时是否已在代码的特定位置设置了变量?这并不总是很明显,因为(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?
关注者
0
被浏览
86
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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




知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看