【发布时间】:2018-01-01 02:45:02
【问题描述】:
考虑这个示例,其中类A 的所有实例的__dict__ 将指向全局字典shared。
shared = {'a': 1, 'b': 2}
class A(object):
def __init__(self):
self.__dict__ = shared
现在让我们测试一些东西:
>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
(1, 2, 1, 2)
>>> b.x = 100
>>> shared
{'a': 1, 'x': 100, 'b': 2}
>>> a.x
100
>>> c = A()
>>> c.a, c.b, c.x
(1, 2, 100)
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
('bar', 'bar', 'bar')
>>> a.__dict__, b.__dict__, c.__dict__
({'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'},
{'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'},
{'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'}
)
一切正常。
现在让我们通过添加一个名为 __dict__ 的属性来稍微调整类 A。
shared = {'a': 1, 'b': 2}
class A(object):
__dict__ = None
def __init__(self):
self.__dict__ = shared
让我们再次运行同一组步骤:
>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
AttributeError: 'A' object has no attribute 'a'
>>> b.x = 100
>>> shared
{'a': 1, 'b': 2}
>>> b.__dict__ # What happened to x?
{'a': 1, 'b': 2}
>>> a.x
AttributeError: 'A' object has no attribute 'x'
>>> c = A()
>>> c.a, c.b, c.x
AttributeError: 'A' object has no attribute 'a'
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
AttributeError: 'A' object has no attribute 'foo'
>>> a.__dict__, b.__dict__, c.__dict__
({'a': 1, 'b': 2, 'foo': 'bar'},
{'a': 1, 'b': 2, 'foo': 'bar'},
{'a': 1, 'b': 2, 'foo': 'bar'}
)
>>> b.x # Where did this come from?
100
根据上述信息,第一种情况按预期工作,但第二种情况没有,因此我想知道添加类级别 __dict__ 属性后发生了什么变化。我们能以任何方式访问现在正在使用的实例字典吗?
【问题讨论】:
-
您不应该添加带有前导和尾随双下划线字符的属性,这是为系统定义的名称保留的。见Reserved classes of identifiers。
-
@martineau 我知道这一点。但这不是这个问题的重点。
-
因此,您想知道解决方法来解决由于您没有遵循指南(其存在是有原因的)而损坏的东西。
-
@martineau 是的。但仅用于学习目的。我不会在实际代码中做类似的事情。
-
您不能直接通过
a.__dict__['foo']之类的方式访问实例的字典吗?
标签: python class python-internals