[Tutor] slots and inheritance - a bit more
Arthur Siegel
ajs@ix.netcom.com
Thu, 4 Jul 2002 16:00:06 -0400
> 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__).
>From What's New in Python 2.2:
>>Finally, it's possible to constrain the list of attributes that can be
referenced on an >>object using the new __slots__ class attribute. Python
objects are usually very >>dynamic; at any time it's possible to define a
new attribute on an instance by just >>doing obj.new_attr=1. This is
flexible and convenient, but this flexibility can also >>lead to bugs, as
when you meant to write obj.template = 'a' but made a typo and >>wrote
obj.templtae by accident.
No reading of the What's New could find any indication that what you
describe as a side effect is other than main purpose of slots. Though I
happen
to believe you.
And it is true that Guido's http://www.python.org/2.2/descrintro.html only
talks of slots in connection with memory issues.
So I'll settle for a refund only on the What's New portion of my investment.
> [Arthur Siegel]
> > But the *functionality* of slots is not inherited
>
> > - 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 would have thought that B's empty __slots__ would override A's __slots__
and leave B with no attribute slots.
The fact is - as you tutor - it is otherwise.
B's __slot__ declaration, in my terminology, "appends" to __slots__
of A - is what I'm learning.
>>> class A(object):
__slots__=("a")
>>> class B(A):
__slots__=("b")
>>> b=B()
>>> b.a=4
>>> print b.a
4
Now, I might get to where I was hoping to get with slots. No objection here
to taking advantage of a side-effect. Basically had concluded I need to
build
an optlist for my **kw args. __slots__ might end up working as that - with
some
side benefits.
> > 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>.
Knowing what I know now, slots might yet do it for me. Hold the check
(escrowed under the normal arrangements).
Art