Why don't have an object() instance a __dict__ attribute by default?

Gabriel Genellina gagsl-py at yahoo.com.ar
Tue Jan 30 19:15:55 EST 2007


En Tue, 30 Jan 2007 20:31:26 -0300, Létező <letezo at fw.hu> escribió:

> I use Python 2.5, Win32 MSI release.
>
> Setting attributes on an empty object does not work:
>
>>>> a=object()
>
>>>> a.x=1
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'x'
>
>
> However using an empty new style class works fine:
>
>>>> class C(object): pass
> ...
>>>> c=C()
>>>> setattr(c, 'x', 1)
>>>>
>
> The dir(c) function indicates, that the C instance has a __dict__  
> attribute.
>
> Why don't have an object() instance a __dict__ attribute by default?

Because it's not needed, and creating an empty dict has some cost. If you  
need a class with __dict__, just inherit from object as you already have  
noted.

> This may need some explanation in the Python manual.

Maybe.

-- 
Gabriel Genellina




More information about the Python-list mailing list