hasattr不测试字典的成员。请改用
in运算符或
.has_key方法:
>>> example = dict(foo='bar')>>> 'foo' in exampleTrue>>> example.has_key('foo')True>>> 'baz' in exampleFalse但是请注意,
dict.has_key()PEP 8样式指南不建议使用该建议,并且已在Python 3中将其完全删除。
顺便说一句,使用可变的类变量会遇到问题:
>>> 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 = {}


