3

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?

1 Answer 1

5

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'>]
[]
Sign up to request clarification or add additional context in comments.

2 Comments

That looks like exactly what I need, thanks. Does this include every class currently imported, or which does it include?
cls.__subclasses__ will list all classes (that have been defined) that derive from cls. (Note that __subclasses__ is a method available to new-style classes (i.e. those that derive from object) only. This won't work for classic classes.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.