Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

django - 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 then several Models that derive from that base class...

class Asset(models.Model):
    name = models.CharField(max_length=500)
    last_update = models.DateTimeField(default=datetime.datetime.now())
    category = models.CharField(max_length=200, default='None')

    class Meta:
        abstract = True

class AssetTypeA(Asset):
    junk = models.CharField(max_length=200)
    hasJunk =  models.BooleanField()

    def __unicode__(self):
        return self.junk

class AssetTypeB(Asset):
    stuff= models.CharField(max_length=200)

    def __unicode__(self):
        return self.stuff

I'd like to be able to detect if anyone adds a new AssetTypeX model and generate the appropriate pages but currently I am maintaining a list manually, is there a way to determine a list of class names for anything that derives from "Asset"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.:

def descendants(aclass):
  directones = aclass.__subclasses__()
  if not directones: return
  for 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...