Get all __slots__ of derived class
I need to initialise all slots of an instance with None. How do I get all slots of a derived class?
Example (which does not work):
class A(object):
__slots__ = "a"
def __init__(self):
# this does not work for inherited classes
for slot in type(self).__slots__:
seta开发者_运维知识库ttr(self, slot, None)
class B(A):
__slots__ = "b"
I could use an additional class attribute which holds the slots (including the inherited) for all classes, like
class A(object):
__slots__ = "a"
all_slots = "a"
def __init__(self):
# this does not work for inherited classes
for slot in type(self).all_slots:
setattr(self, slot, None)
class B(A):
__slots__ = "b"
all_slots = ["a", "b"]
but that seems suboptimal.
Any comments are appreciated!
Cheers,
Jan
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 chain
slots = 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)
精彩评论