Python对字典列表值的hasattr总是返回false? [英] Python's hasattr on list values of dictionaries always returns false?
问题描述
我有一个字典,有时会收到不存在的键的调用,因此我尝试使用hasattr
和getattr
处理这些情况:
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屋!