Home > database >  See all inherited classes in python
See all inherited classes in python

Time:02-25

So I've done a bit of research online and it seems like the __subclasses__ method returns all the inherited classes for a python object (relevant stack overflow question)

On python3.8 I then tried the following:

class A:
    a = 1
      
class B:
    b = 2
    
class C(A, B):
    c = 3

obj = C()
print('a: ', obj.a)
print('subclasses: ', C.__subclasses__())

and I get out

a: 1
subclasses: []

this shows that class C successfully inherits A and B, however they don't show up with the subclasses method? So is there something I'm missing in the __subclasses__ method, or has the method changed for python 3.8?

CodePudding user response:

just combining the answerts from above :

  1. my_class.__subclasses__ will return the classes, which subclass from my_class

  2. C.__mro__ shows the inheritence hierarchy in your case : (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)

  object
   /  \
  A    B
   \  /
    C

In short, __subclasses__ goes down the object hierarchy ladder and the __mro__ goes up. Good luck :)

  • Related