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?
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'>]
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With