Reputation: 19969
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?
Upvotes: 3
Views: 103
Reputation: 879421
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'>]
[]
Upvotes: 5