python检测某个变量是否有定义的方法,python变量
python检测某个变量是否有定义的方法,python变量
本文实例讲述了python检测某个变量是否有定义的方法。分享给大家供大家参考。具体如下:
第一种方法使用内置函数locals():
'testvar' in locals().keys()
第二种方法使用内置函数dir():
'testvar' in dir()
第三种方法使用内置函数vars():
vars().has_key('testvar')
测试如下:
#testvar未定义 In [1]: 'testvar' in locals().keys() Out[1]: False In [2]: 'testvar' in dir() Out[2]: False In [3]: vars().has_key('testvar') Out[3]: False #定义testvar In [4]: testvar=1 In [5]: 'testvar' in locals().keys() Out[5]: True In [6]: 'testvar' in dir() Out[6]: True In [7]: vars().has_key('testvar') Out[7]: True
还有使用try...except...自己定义的,总之方法很多.
希望本文所述对大家的Python程序设计有所帮助。
相关内容
- Python中subprocess模块用法实例详解,pythonsubprocess
- Python使用matplotlib绘制动画的方法,
- Python使用reportlab将目录下所有的文本文件打印成pdf的方
- python获取指定目录下所有文件名列表的方法,
- Python使用matplotlib实现在坐标系中画一个矩形的方法,
- Python使用shelve模块实现简单数据存储的方法,pythonshe
- python使用wxpython开发简单记事本的方法,pythonwxpython
- python任务调度实例分析,python任务调度
- Python中处理字符串之islower()方法的使用简介,pythonisl
- python绘图方法实例入门,python绘图实例
评论关闭