获取派生类的所有__slots__

时间:2011-07-16 22:46:40

标签: python inheritance slots

我需要使用None初始化实例的所有插槽。如何获取派生类的所有插槽?

示例(不起作用):

class A(object):
    __slots__ = "a"

    def __init__(self):
        # this does not work for inherited classes
        for slot in type(self).__slots__:
            setattr(self, slot, None)

class B(A):
    __slots__ = "b"

我可以使用一个额外的class属性来保存所有类的槽(包括继承的),比如

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"]

但这似乎不是最理想的。

感谢任何评论!

干杯,

2 个答案:

答案 0 :(得分:14)

首先,它是

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

制作一个包含B的__slots__或其任何父类所包含的所有元素的列表将是:

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

答案 1 :(得分:9)

您希望遍历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)

您可以看到这在派生类中按预期工作:

class B(A):
    __slots__ = ('z',)

>>> b = B()

>>> b.x, b.y, b.z
<<< (None, None, None)