Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance - going from base class to derived one

Given a class and other classes that extend it either directly or indirectly. Is there a way to get all the classes that directly extend the original class.

class Alpha(object):
    @classmethod
    def get_derivatives(cls):
        return [Beta, ] # when called from Alpha
        return [] # when called from Beta

class Beta(Alpha):
    pass

I'm guessing there are some complications or it is impossible altogether. There would have to be some specification as to where the derived classes are defined, which would make things tricky...

Is my best bet to hard-code the derived classes into the base one?

like image 356
Mark Avatar asked Jun 26 '26 21:06

Mark


1 Answers

Perhaps you are looking for the __subclasses__ method:

class Alpha(object):
    @classmethod
    def get_derivatives(cls):
        return cls.__subclasses__() 

class Beta(Alpha):
    pass

print(Alpha.get_derivatives())
print(Beta.get_derivatives())

yields

[<class '__main__.Beta'>]
[]
like image 127
unutbu Avatar answered Jun 29 '26 11:06

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!