[Tutor] slots and inheritance - a bit more

Tim Peters tim.one@comcast.net
Thu, 04 Jul 2002 13:24:48 -0400


[Arthur Siegel]
> I also seem to be discovering that one
> cannot multiherit from 2 classes derived
> from "object", each with slots defined.

That's true.

> I guess this only seems surprising in light
> of that fact that the slots are not inherited.

Slots are inherited.  What have you seen that made you believe they're not
inherited?

>>> class A(object):
...     __slots__ = 'a'
...
>>> class B(A):
...     pass
...
>>> b = B()
>>> b.a = 12
>>> b.x = 42
>>> b.a
12
>>> b.x
42
>>> b.__dict__  # only 'x' is in the dict; 'a' is stored in inherited slot
{'x': 42}
>>>

BTW, note that __slots__ are really an optimization gimmick.  There's no
reason to bother with them unless you have a great many instances of some
class and need to reduce memory use.  Then they can help, but then you also
have to live with the restrictions the use of __slots__ impose.