开发者

Dictionary of class subclasses

开发者 https://www.devze.com 2023-03-01 00:12 出处:网络
Whether there is a way to make the dictionary of all class inheritances ? Something l开发者_如何学编程ike

Whether there is a way to make the dictionary of all class inheritances ?

Something l开发者_如何学编程ike

 class MagikClass :

       pass

 class A(MagikClass) :

       __name__ = "A"

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


Here is a solution that adds an attribute _derived to each class, containing the derived classes of that class:

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

prints

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

精彩评论

暂无评论...
验证码 换一张
取 消