__slots__ in derived class

Kay Schluehr kay.schluehr at gmx.net
Wed Mar 15 14:07:50 CET 2006


Schüle Daniel wrote:
> Hello,
>
> consider this code
>
>  >>> class A(object):
> ...     def __init__(self):
> ...             self.a = 1
> ...             self.b = 2
> ...
>  >>> class B(A):
> ...     __slots__ = ["x","y"]
> ...
>  >>> b=B()
>  >>> b.a
> 1
>  >>> b.b
> 2
>  >>> b.x = 100
>  >>> b.y = 100
>  >>> b.z = 100
>
> no exception here
> does __slots__ nothing when used in derived classes?
>
>
>  >>>
>  >>>
>  >>> class Z(object):
> ...     __slots__ = ["x","y"]
> ...
>  >>> z=Z()
>  >>> z.x = 100
>  >>> z.y = 100
>  >>> z.z = 100
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: 'Z' object has no attribute 'z'
>  >>>
>
> here it works like expected
>
> Regards, Daniel

I would expect that A has to define its own __slots__ too.

The following code should work as expected and makes also sense with
the memory optimization considerations that motivated introduction of
the __slots__ variable.

class A(object):
    __slots__ = ["a","b"]
    def __init__(self):
        self.a = 1
        self.b = 2

class B(A):
    __slots__ = ["x","y"]

Kay




More information about the Python-list mailing list