品易云推流 关闭
文章详情页
文章 > Python常见问题 > python如何查找是否存在某个变量?

python如何查找是否存在某个变量?

头像

yang

2020-05-07 16:04:463417浏览 · 0收藏 · 0评论

python中可以使用locals()、dir()、vars()等函数来查询变量是否存在。

  • locals() 函数会以字典类型返回当前位置的全部局部变量。

  • dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。

  • vars() 函数返回对象object的属性和属性值的字典对象。

示例:

res1 = 'test' in locals().keys()
res2 = 'test' in dir()
res3 = 'test' in vars().keys()
print(res1,res2,res3)  # 变量test暂时还没有定义,返回False
test = ""  # 定义变量test
res4 = 'test' in locals().keys()
res5 = 'test' in dir()
res6 = 'test' in vars().keys()
print(res4,res5,res6)  # 变量test已经被定义了,返回True

更多Python知识请关注Python视频教程栏目。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图