[Tutor] slots and inheritance

Arthur Siegel ajs@ix.netcom.com
Thu, 4 Jul 2002 11:05:27 -0400


Playing with new style classes.
I am particularly interested in the slots feature, since
it is quite common for me to typo when sending a keyword
argument when initializing a class instance. It never seemed quite
right to me that the typo would silently pass, and I
might not even notice that the argument I thought I sent was
having no impact.

(Yeah, I know with me whining about change all the time.  
Well I certainly have no intention of not making my best
effort to take advantage of  new features. I guess we all have
our own list of which are the "good" ones.) 

So --

>>> class A(object):
               __slots__=("x","y","z")
>>> a=A()
>>> a.x=1
>>> print a.x
1
>>> a.w=4
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in ?
    a.w=4
AttributeError: 'A' object has no attribute 'w'

All as advertised.

Now:

>>> class B(A):
                     pass

>>> b=B()
>>> b.w=4
>>> print b.w
4

So apparently slots are not inherited. 
Which surprised me.

I am thinking:

class B(A):
    __slots__ = A.__slots__

is the way to go and say

class B(A):
   __slots__ = A.__slots__ + ("u","v")

let's say if I want to add attributes to B not 
legal for A.

Is this by the book? (Were there a book)

Art