Python的字典列表值的hasattr总是返回false?

Chr*_*ele 27 python dictionary class list hasattr

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

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
Run Code Online (Sandbox Code Playgroud)

第一次运行integer = 1:

current info: {}
False
[]
current info: {'foo': [1]}
Run Code Online (Sandbox Code Playgroud)

再次运行此代码integer = 2:

instance.add_to_info("foo", 2)

current info: {'foo': [1]}
False
[]
current info: {'foo': [2]}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 37

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

>>> example = dict(foo='bar')
>>> 'foo' in example
True
>>> example.has_key('foo')
True
>>> 'baz' in example
False
Run Code Online (Sandbox Code Playgroud)

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

顺便说一下,使用可变类变量会遇到问题:

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

在您的初始化__init__:

class State(object):
    info = None

    def __init__(self):
        self.info = {}
Run Code Online (Sandbox Code Playgroud)


kat*_*her 5

字典键与对象属性不同

thing1 = {'a', 123}
hasattr(thing1, 'a') # False
class c: pass
thing2 = c()
thing2.a = 123
hasattr(thing2, 'a') # True
Run Code Online (Sandbox Code Playgroud)

  • 啊。这让我发疯。谢谢分享例子。 (2认同)