Get all __slots__ of derived class Get all __slots__ of derived class python python

Get all __slots__ of derived class


First of all, it's

class A(object):    __slots__ = ('a',)class B(A):    __slots__ =  ('b',)

Making a list that contains all elements contained by __slots__ of B or any of its parent classes would be:

from itertools import chainslots = chain.from_iterable(getattr(cls, '__slots__', []) for cls in B.__mro__)


You want to iterate through each class in the MRO:

class A(object):    __slots__ = ('x', 'y')    def __init__(self):        for slots in [getattr(cls, '__slots__', []) for cls in type(self).__mro__]:            for attr in slots:                setattr(self, attr, None)

You can see that this works as expected in the derived class:

class B(A):    __slots__ = ('z',)>>> b = B()>>> b.x, b.y, b.z<<< (None, None, None)