Python判断变量是否已经定义的方法

WBOY
Release: 2016-06-06 11:31:58
Original
1391 people have browsed it

Python判断变量是否已经定义是一个非常重要的功能,本文就来简述这一功能的实现方法。

其实Python中有很多方法可以实现判断一个变量是否已经定义了。这里就举出最常用的两种作为示例,如下所示:

方法一:try except方法:

def isset(v): 
   try : 
     type (eval(v)) 
   except : 
     return  0  
   else : 
     return  1  
Copy after login

用法:

if isset('user_name'): 
  print 'user_name is defined' 
else 
  print 'user_name is not defined' 

Copy after login

方法二:使用命名空间:

'varname' in locals().keys()
'varname' in  dir()

Copy after login

本文示例仅作参考,读者还可以继续在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