打印SuperClass中的所有SubClass和SubClass中的所有SuperClass

时间:2015-08-31 09:20:53

标签: python

我希望在SuperClass中打印所有子类,并在子类中打印所有超类:

class SuperClass():
    def Print(self):
        print('my sub classes are : ')
        #print all childs

class Sub1(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

class Sub2(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

SuperClass有Print可以打印所有继承的类,而Sub有Print方法可以打印所有的SuperClasses。怎么做?

1 个答案:

答案 0 :(得分:5)

Python类有三个有用的属性:

  • class.__subclasses__();返回类的所有子类的方法。

  • class.__bases__,是当前班级的直接父类的元组。

  • class.__mro__,在当前类层次结构中包含所有类的元组。在该元组中查找当前的类对象,后面的所有内容都是父类,直接或间接。

使用以下内容:

class SuperClass(object):
    def print(self):
        print('my sub classes are:', ', '.join([
            cls.__name__ for cls in type(self).__subclasses__()]))

class Sub1(SuperClass):
    def print(self):
        print('My direct parents are:', ', '.join([
            cls.__name__ for cls in type(self).__bases__]))
        all_parents = type(self).__mro__
        all_parents = all_parents[all_parents.index(Sub1) + 1:]
        print('All my parents are:', ', '.join([
            cls.__name__ for cls in all_parents]))

演示:

>>> SuperClass().print()
my sub classes are: Sub1
>>> Sub1().print()
My direct parents are: SuperClass
All my parents are: SuperClass, object