[Tutor] slots and inheritance - a bit more

Tim Peters tim.one@comcast.net
Thu, 04 Jul 2002 14:55:12 -0400


[Arthur Siegel]
> But the *functionality* of slots is not inherited

I'm not sure what you mean.  The goal of slots is to save memory, and the
more-efficient memory layout at the C level is inherited (indeed, that's why
you can't inherit from more than one base class with __slots__).

> - unless I kill B's __dict__.  Correct? If so, is that doable?

In a single-inheritance hierarchy, you can specify __slots__ at all, no, or
any subset of levels.  Instances of a level that defines __slots__  have no
dicts; instances of a level that doesn't have __slots__ do have dicts.  For
example,

class A(object):
    __slots__ = 'a'

class B(A):
    __slots__ = []

Then an instance of B has no dict (because it *also* specifies __slots__,
albeit an empty set of slots), and can only use the inherited 'a' as an
attribute name.

> I kind of thought the restriction - as in object.kolor = "blue" when you
> meant object.color= "blue" was of the essence of slots.

That's a *consequence* of the memory-saving aspect.  Dicts are rather large
data structures, and the essence of slots is that an object of a class using
__slots__ has no dict.  Without a dict, the names of all attributes have to
be known at class-creation time, as there's no longer any way to add new
attributes dynamically:  the memory layout is fixed for all time when the
class is created.  It's legitimate to think of that as a feature, or to
think of that as a restriction, but in either case the lack of dynamic
attribute creation is a consequence and not a goal.  If Guido could have
made the memory layout more efficient without sacrificing dynamic attribute
creation, he would have.

> But if you mean the multi-heritance restriction - yes.  Happens to be a
> deal killer in my case.

Damn!  We'll send you a refund check at close-of-business Monday <wink>.