Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #70531

Re: object().__dict__

From Ben Finney <ben@benfinney.id.au>
Subject Re: object().__dict__
Date 2014-04-23 16:09 +1000
References <51d9b7f1-3511-4110-adb2-aa2226bd7a3c@lists.xtsubasa.org>
Newsgroups comp.lang.python
Message-ID <mailman.9453.1398233367.18130.python-list@python.org> (permalink)

Show all headers | View raw


Pavel Volkov <sailor@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: object().__dict__ Ben Finney <ben@benfinney.id.au> - 2014-04-23 16:09 +1000

csiph-web