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 ?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.