目录

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

目录

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

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

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

方法一:try except方法:

1 2 3 4 5 6 7def isset(v): try : type ( eval (v)) except : return 0 else : return 1

用法:

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

方法二:使用命名空间:

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

本文示例仅作参考,读者还可以继续在Python的编程实践中继续总结其他的方法。