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'>}
精彩评论