简体   繁体   English

打印超类中的所有子类以及子类中的所有超类

[英]print all SubClass in a SuperClass and all SuperClass in a SubClass

I want in SuperClass print all subClasses and in a subClasses print all SuperClasses: 我想要在SuperClass中打印所有子类,并在子类中打印所有的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 has Print that print all classes that inherit from , and Sub has Print method that print all his SuperClasses . SuperClass具有Print可以打印从其继承的所有类,而Sub具有Print方法可以打印其所有SuperClasses。 how do that ? 怎么办?

Python classes have three attributes that help here: Python类具有三个属性,可在此处提供帮助:

  • class.__subclasses__() ; class.__subclasses__() ; a method that returns all subclasses of the class. 返回该类的所有子类的方法。

  • class.__bases__ , a tuple of the direct parent classes of the current class. class.__bases__ ,当前类的直接父类的元组。

  • class.__mro__ , a tuple with all classes in the current class hierarchy. class.__mro__ ,具有当前类层次结构中所有类的元组。 Find the current class object in that tuple and everything following is a parent class, directly or indirectly. 在该元组中找到当前的类对象,其后的所有对象都是直接或间接的父类。

Using these that gives: 使用这些可以得到:

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

Demo: 演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM