免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 62332 | 回复: 13
打印 上一主题 下一主题

[Python基础]如何判断一个变量是否存在 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-27 16:23 |只看该作者 |倒序浏览
在Python中如何判断一个变量是否已经存在?
谢谢!

论坛徽章:
0
2 [报告]
发表于 2009-11-27 16:54 |只看该作者
if yourvariable:
    blablabal

论坛徽章:
0
3 [报告]
发表于 2009-11-27 17:01 |只看该作者
不晓得。。关注

我一般是定义None 再用if判断 呵呵~  很傻瓜的办法~~

论坛徽章:
0
4 [报告]
发表于 2009-11-27 18:50 |只看该作者
原帖由 leo_ss_pku_cu 于 2009-11-27 16:54 发表
if yourvariable:
    blablabal


你这个方式有问题
# python
Python 2.6 (r26:66714, Jun  8 2009, 16:07:26)
[GCC 4.4.0 20090506 (Red Hat 4.4.0-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="b"
>>> if a: print a
...
b
>>> if b: print b
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

还是会出现问题。

谢谢你的回复!

论坛徽章:
0
5 [报告]
发表于 2009-11-27 21:19 |只看该作者
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

    ****************************************************************
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface.  This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    ****************************************************************
   
IDLE 1.2.4      
>>> dir()
['__builtins__', '__doc__', '__name__']
>>> 's' in dir()
False
>>> s = 'hello, python'
>>> 's' in dir()
True
>>>

论坛徽章:
0
6 [报告]
发表于 2009-11-27 21:22 |只看该作者
不知hasattr(object,name),是否可满足你的要求.
比如你定义一个类(与之类似就可):
class Test:
      t = 1

if hasattr(Test,'t'):
    print t


......

论坛徽章:
0
7 [报告]
发表于 2009-11-27 23:06 |只看该作者
try:
     whatever
except NameError:
     print "whatever not defined"

论坛徽章:
0
8 [报告]
发表于 2009-11-28 03:08 |只看该作者
原帖由 wzhuzhu 于 2009-11-27 00:23 发表
在Python中如何判断一个变量是否已经存在?
谢谢!


5楼正解。

论坛徽章:
1
天蝎座
日期:2013-10-23 21:11:03
9 [报告]
发表于 2009-11-28 05:16 |只看该作者
搜了一下
http://www.cnblogs.com/starspace/archive/2008/12/03/1347007.html
python中检测某个变量是否有定义

第一种方法:
      'var'   in   locals().keys()

第二种方法:
    try:
         print   var
    except   NameError:
         print   'var   not   defined'

第三种方法:
      'var'   in   dir()

论坛徽章:
0
10 [报告]
发表于 2009-11-28 16:04 |只看该作者
原帖由 openspace 于 2009-11-28 05:16 发表
搜了一下

多谢大家的回复。
感谢,问题解决!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP