本文介绍了查找从python中的给定基类派生的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来获取从Python中的特定基类派生的所有类的列表。

I'm looking for a way to get a list of all classes that derive from a particular base class in Python.

更具体地说,我使用的是Django,我有一个抽象的基础模型,然后是几个派生自这个基类的模型...

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

我想要检测是否有人添加了一个新的AssetTypeX模型并生成相应的页面,但是目前我正在手动维护列表确定从资产派生的任何东西的类名列表的方法?

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"?

推荐答案

资产.__子类__()给出 子类资产,但这是否足以取决于是否立即部分是一个问题 - 如果你想让所有的后代达到任何级别,你需要递归扩展,例如:

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.

这篇关于查找从python中的给定基类派生的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 02:24