Python对字典列表值的hasattr总是返回false? [英] Python's hasattr on list values of dictionaries always returns false?

查看:159
本文介绍了Python对字典列表值的hasattr总是返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,有时会收到不存在的键的调用,因此我尝试使用hasattrgetattr处理这些情况:

I have a dictionary that sometimes receives calls for non-existent keys, so I try and use hasattr and getattr to handle these cases:

key_string = 'foo'
print "current info:", info
print hasattr(info, key_string)
print getattr(info, key_string, [])
if hasattr(info, key_string):
    array = getattr(info, key_string, [])
array.append(integer)
info[key_string] = array
print "current info:", info

第一次使用integer = 1运行:

current info: {}
False
[]
current info: {'foo': [1]}

使用integer = 2再次运行此代码:

instance.add_to_info("foo", 2)

current info: {'foo': [1]}
False
[]
current info: {'foo': [2]}

第一次运行显然很成功({'foo': [1]}),但是hasattr返回false,并且getattr第二次使用默认的空白数组,在此过程中丢失了1的值!为什么会这样?

The first run is clearly successful ({'foo': [1]}), but hasattr returns false and getattr uses the default blank array the second time around, losing the value of 1 in the process! Why is this?

推荐答案

hasattr不测试字典的成员.请使用in运算符,或使用.has_key方法:

hasattr does not test for members of a dictionary. Use the in operator instead, or the .has_key method:

>>> example = dict(foo='bar')
>>> 'foo' in example
True
>>> example.has_key('foo')
True
>>> 'baz' in example
False

但是请注意,PEP 8样式指南建议不要使用dict.has_key(),并且在Python 3中已将其完全删除.

But note that dict.has_key() has been deprecated, is recommended against by the PEP 8 style guide and has been removed altogether in Python 3.

偶然地,使用可变的类变量会遇到问题:

Incidentally, you'll run into problems by using a mutable class variable:

>>> class example(object):
...     foo = dict()
...
>>> A = example()
>>> B = example()
>>> A.foo['bar'] = 'baz'
>>> B.foo
{'bar': 'baz'}

在您的__init__中将其初始化:

class State(object):
    info = None

    def __init__(self):
        self.info = {}

这篇关于Python对字典列表值的hasattr总是返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆