python如何查找是否存在某个变量?
发布时间:2026-04-27 15:48:02

locals()可用于python、dir()、vars()等函数查询变量是否存在。
locals()函数将以字典类型返回当前位置的所有局部变量。
dir()函数不带参数时,返回当前范围内的变量、方法和定义类型列表;带参数时,返回参数的属性和方法列表。
vars()函数返回对象object的属性和属性值的字典对象。
示例:
res1='test'inlocals().keys() res2='test'indir() res3='test'invars().keys() print(res1、res2、res3)#变量test尚未定义,返回False test=""#定义变量test res4='test'inlocals().keys() res5='test'indir() res6='test'invars().keys() print(res4、res5、res6)#变量test已被定义,返回truee
请关注Python视频教程栏目,了解更多Python知识。
下一篇 python脚本中有乱码怎么解决
