__slots__ in derived class

  • Thread starter =?ISO-8859-1?Q?Sch=FCle_Daniel?=
  • Start date
?

=?ISO-8859-1?Q?Sch=FCle_Daniel?=

Hello,

consider this code
.... def __init__(self):
.... self.a = 1
.... self.b = 2
........ __slots__ = ["x","y"]
....
no exception here
does __slots__ nothing when used in derived classes?

.... __slots__ = ["x","y"]
....Traceback (most recent call last):

here it works like expected

Regards, Daniel
 
K

Kay Schluehr

Schüle Daniel said:
Hello,

consider this code
... def __init__(self):
... self.a = 1
... self.b = 2
...... __slots__ = ["x","y"]
...
no exception here
does __slots__ nothing when used in derived classes?

... __slots__ = ["x","y"]
...Traceback (most recent call last):

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
 
D

Duncan Booth

Schüle Daniel said:
consider this code
... def __init__(self):
... self.a = 1
... self.b = 2
...... __slots__ = ["x","y"]
...
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.
 
A

Aahz

does __slots__ nothing when used in derived classes?

Short answer: don't use __slots__ until you're comfortable writing
metaclasses and decorators. __slots__ are a performance hack strictly
for advanced users, and if you think you need them, you probably don't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top