__slots__ in derived class

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 15 08:44:55 EST 2006


Schüle Daniel wrote:

> 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?

__slots__ is intended as a way to reduce memory consumption. It was never 
intended as a protection mechanism.

The slots which are available in a class only add to the attributes 
available in the base class. You can hide base class slots by defining a 
slot of the same name, but you cannot remove them.

Your base class has a __dict__ attribute and therefore all instances of the 
base class or any derived classes also have a __dict__ attribute.



More information about the Python-list mailing list