__slots_ and inheritance
Blair Hall
b.hall at irl.cri.nz
Thu Apr 10 23:08:37 EDT 2003
I'm having trouble understanding exactly how __slots__
is supposed to behave when one class is derived from
another. For example:
# First case: works as I would expect
class A(object):
__slots__ = ('x','y')
def __init__(self):
pass
class B(A):
__slots__ = ('z',)
def __init__(self):
A.__init__(self)
b = B()
b.x = 1
b.z = 3
# b.c = 3 # fails
This script would fail at the last line as expected, because
there is no attribute 'c' allowed. However,
# Second case: class B has no slots
class A(object):
__slots__ = ('x','y')
def __init__(self):
pass
class B(A):
def __init__(self):
A.__init__(self)
b = B()
b.x = 1
b.c = 3 # passes
In this case the attribute 'c' can be created. Perhaps a __slots__
in the base class does not prevent attributes from being added
to the derived class (I guess this is good). But,
# Third case: class A has no slots
class A(object):
def __init__(self):
pass
class B(A):
__slots__ = ('z',)
def __init__(self):
A.__init__(self)
b = B()
b.c = 3 # passes
in this case, although the class B has slots its base class
does not. This seems to allow instances of B to ignore their
own __slots__ requirements. This, to my mind, is a problem:
it seems to require knowledge of the __slots__ in all
base classes.
Can anyone steer me towards a better understanding of __slots__?
More information about the Python-list
mailing list