Finding All Classes That Derive From A Given Base Class In Python
I'm looking for a way to get a list of all classes that derive from a particular base class in Python. More specifically I am using Django and I have a abstract base Model and the
Solution 1:
Asset.__subclasses__()
gives the immediate subclasses of Asset
, but whether that's sufficient depends on whether that immediate part is a problem for you -- if you want all descendants to whatever number of levels, you'll need recursive expansion, e.g.:
defdescendants(aclass):
directones = aclass.__subclasses__()
ifnot directones: returnfor c in directones:
yield c
for x in descendants(c): yield x
Your examples suggest you only care about classes directly subclassing Asset
, in which case you might not need this extra level of expansion.
Post a Comment for "Finding All Classes That Derive From A Given Base Class In Python"