Home > Backend Development > Python Tutorial > python检测某个变量是否有定义的方法

python检测某个变量是否有定义的方法

WBOY
Release: 2016-06-10 15:12:01
Original
1107 people have browsed it

本文实例讲述了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 

Copy after login

还有使用try...except...自己定义的,总之方法很多.

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template