0

I want in SuperClass print all subClasses and in a subClasses print all SuperClasses:

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 . how do that ?

Zero Days
  • 851
  • 1
  • 11
  • 22

1 Answers1

5

Python classes have three attributes that help here:

  • 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.__mro__, a tuple with all classes in the current class hierarchy. 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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343