类子类字典

时间:2011-04-26 14:20:23

标签: python oop

是否有办法制作所有类继承的字典?

这样的东西
 class MagikClass :

       pass

 class A(MagikClass) :

       __name__ = "A"

 print magik_dict # -> { "A": A }

1 个答案:

答案 0 :(得分:4)

这是一个为每个类添加属性_derived的解决方案,包含该类的派生类:

class Meta(type):
    def __new__(cls, name, bases, dict_):
        new_class = type.__new__(cls, name, bases, dict_)
        new_class._derived = {}
        if isinstance(bases[0], Meta):
            bases[0]._derived[name] = new_class
        return new_class

class Magic(object):
    __metaclass__ = Meta

class A(Magic):
    pass

class B(Magic):
    pass

print Magic._derived

打印

{'A': <class '__main__.A'>, 'B': <class '__main__.B'>}