__dict__ strangeness

Ziga Seilnacht ziga.seilnacht at gmail.com
Sat Mar 18 23:25:01 CET 2006


Georg Brandl wrote:
> Hi,
>
> can someone please tell me that this is correct and why:
>
> >>> class C(object):
> ...     pass
> ...
> >>> c = C()
> >>> c.a = 1
> >>> c.__dict__
> {'a': 1}
> >>> c.__dict__ = {}
> >>> c.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'C' object has no attribute 'a'
> >>>
> >>> class D(object):
> ...     __dict__ = {}
> ...
> >>> d = D()
> >>> d.a = 1
> >>> d.__dict__
> {}
> >>> d.__dict__ = {}
> >>> d.a
> 1
>
> Thanks,
> Georg

Here is another example that might help:

>>> class E(object):
...     __dict__ = {'a': 1}
...
>>> e = E()
>>> e.__dict__
{'a': 1}
>>> E.__dict__
<dictproxy object at 0x00A81930>
>>> E.__dict__['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'a'
>>> E.__dict__['__dict__']
{'a': 1}

Ziga




More information about the Python-list mailing list