用户工具

站点工具


python-hacks:variable-defined

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

python-hacks:variable-defined [2011/07/05 15:09] (当前版本)
行 1: 行 1:
 +====== Python中如何判断变量是否已经定义 ======
 +
 +Python中其实有蛮多方法可以判断一个变量是否已经定义了。
 +===== 方法一:try except =====
 +
 +<code python>
 +def  isset(v):  ​
 +     try :  ​
 +         type (eval(v))  ​
 +      except :  ​
 +          return ​  ​0 ​  
 +      else :  ​
 +          return ​  ​1 ​  
 +</​code>​
 +
 +用法:
 +<code python>
 +if isset('​user_name'​):  ​
 +    print '​user_name is defined'  ​
 +else  ​
 +    print '​user_name is not defined'  ​
 +</​code>​
 +===== 方法二:使用命名空间 =====
 +
 +<code python>
 +'​varname'​ in locals().keys()
 +'​varname' ​ in   dir()
 +</​code>​
 +
  
python-hacks/variable-defined.txt · 最后更改: 2011/07/05 15:09 (外部编辑)