__slots__ and multiple inheritance
Dave Reed
dreed at capital.edu
Sat Dec 14 16:15:07 EST 2002
On Saturday 14 December 2002 15:53, Carl Banks wrote:
> Dave Reed wrote:
> >
> > __slots__ doesn't seem to work as I expect when I use
mixins/multiple
> > inheritance:
> >
> > I've got a BaseSQL class (see code at bottom of message) in which I
> > define __slots__ (I started using it so pychecker didn't complain
> > about me using the instance variables from the other base class). I
> > left out "values" from __slots__, but it still lets me assign to
> > self.values.
> >
> > Also, If I put the same __slots__ in the StudentSQL class, I get the
> > error:
> >
> > class Student(BaseSQL, StudentSQL):
> > TypeError: multiple bases have instance lay-out conflict
> >
> > Can anyone explain to me how this should work?
>
> It doesn't work at all. It seems kind of stupid at first, but you
> can't inherit from two classes with slots (well, unless those classes'
> slots are all inherited from a common base class).
I wasn't very clear - without the __slots__ in the the StudentSQL
class, then it happily lets me access self.values in the BaseSQL class
even though 'values' is not in the BaseSQL __slots__ list (and the
other instance variables are). I expected to get an error when I tried
to set self.values, but didn't.
Regarding the second point:
I read the following from Guido's "Unifying Types and Classes in
Python 2.2" but I don't quite understand it.
There's no check to prevent name conflicts between the slots defined
in a class and the slots defined in its base classes. If a class
defines a slot that's also defined in a base class, the instance
variable defined by the base class slot is inaccessible (except by
retrieving its descriptor directly from the base class; this could
be used to rename it). Doing this renders the meaning of your
program undefined; a check to prevent this may be added in the
future.
It appears to me that you could have __slots__ in both base classes
as long as they intersection of the lists is empty (I'm pretty certain
I tried that and it didn't work either).
> The reason for this is that slots have fixed positions in the object's
> low-level structure. One base class puts its slots at position x in
> the structure; another base class also puts slots at position x. You
> can't multiply inherit from both of them because of the clash.
Thanks,
Dave
More information about the Python-list
mailing list