Consider this example where the __dict__
of all instances of a class A
will point to a global dict shared
.
shared = {'a': 1, 'b': 2}
class A(object):
def __init__(self):
self.__dict__ = shared
Now let's test a few things:
>>> 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'}
)
All works as expected.
Now let's tweak class A
a little by adding an attribute named __dict__
.
shared = {'a': 1, 'b': 2}
class A(object):
__dict__ = None
def __init__(self):
self.__dict__ = shared
Let's run the same set of steps again:
>>> 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
Based on the above information the first case worked as expected but the second one didn't and hence I would like to know what changed after the adding class level __dict__
attribute. And can we access the instance dictionary being used now in any way?