object().__dict__

Ben Finney ben at benfinney.id.au
Wed Apr 23 02:09:14 EDT 2014


Pavel Volkov <sailor at lists.xtsubasa.org> writes:

> The attribute list is different now and there's no __dict__ and the
> object does not accept new attributes.
> Please explain what's going on.

It's a leaky abstraction, unfortunately.

By default, all user-defined types will provide their instances with a
‘__dict__’ attribute, whic is a mapping to store the instance's
attributes.

But some types don't have that, and ‘object’ is one of them. It
deliberately overrides the default behaviour, and has no ‘__dict__’ for
its instances.

    >>> foo = object()

    >>> foo.bar = "spam"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'object' object has no attribute 'bar'

    >>> foo.__dict__
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'object' object has no attribute '__dict__'

Your user-defined types, even though they inherit from ‘object’, will
get a ‘__dict__’ as normal::

    >>> class Bag:
    >>>     """ A simple type to hold attributes. """

    >>> Bag.__mro__
    (<class '__main__.Bag'>, <class 'object'>)

    >>> foo = Bag()
    >>> foo.bar = "spam"
    >>> foo.__dict__
    {'bar': 'spam'}

See the discussion of ‘__slots__’, and note also that it's not
recommended to use this unless you know exactly why you need it
<URL:https://docs.python.org/3/reference/datamodel.html#slots>.

I consider it a wart of Python that its ‘object’ instances lack the
ability to gain arbitrary attributes in the way you expect.

-- 
 \      “Every man would like to be God, if it were possible; some few |
  `\          find it difficult to admit the impossibility.” —Bertrand |
_o__)                    Russell, _Power: A New Social Analysis_, 1938 |
Ben Finney




More information about the Python-list mailing list