如何检查Python变量是否存在?
我们使用以下代码检查python中是否存在变量。
示例
x =10
class foo:
g = 'rt'
def bar(self):
m=6
print (locals())
if 'm' in locals():
print ('m is local variable')
else:
print ('m is not a local variable')
f = foo()f.bar()
print (globals())
if hasattr(f, 'g'):
print ('g is an attribute')
else:
print ("g is not an attribute")
if 'x' in globals():
print ('x is a global variable')输出结果
我们得到以下输出
{'self': <__main__.foo instance at 0x0000000002E24EC8>, 'm': 6}
m is local variable
{'f': <__main__.foo instance at 0x0000000002E24EC8>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/Users/nhooo1/~.py', '__package__': None, 'x': 10, '__name__': '__main__', 'foo': <class __main__.foo at 0x0000000002D29828>, '__doc__': None}
g is an attribute
x is a global variable
Process finished with exit code 0热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短