[英]How do I list all classes of a given type in a python file?
I use django, and have a lengthy models.py file. 我使用django,并且有一个冗长的models.py文件。
class Foo(models.Model):
name = models.CharField()
class Bar(models.Model):
name = models.CharField()
class Fab(models.Model):
name = models.CharField()
Is there a way to make a list of all the classes in the file which are an instance of (models.Model)? 有没有办法列出文件中所有属于(models.Model)实例的类?
Django provides some utility methods to get model classes. Django提供了一些实用程序方法来获取模型类。
from django.db.models.loading import get_models, get_app
app = get_app('myappname')
models = get_models(app)
When you say: 当你说:
... classes in the file which are an instance of ...
...文件中的类是...的实例
i think you mean "...classes in the file which are subclass of...". 我认为您的意思是“ ...文件中属于...子类的类”。 If so:
如果是这样的话:
classes = [cls for cls in dir(module)
if issubbclass(getattr(module, cls), models.Model)]
The inspect
module might help you. inspect
模块可能会为您提供帮助。 Here's some code from a plugin manager class I wrote that might serve as an example. 这是我编写的插件管理器类中的一些代码,可以作为示例。
def load_plugin_file(self, pathname):
'''Return plugin classes in a plugin file.'''
name, ext = os.path.splitext(os.path.basename(pathname))
f = file(pathname, 'r')
module = imp.load_module(name, f, pathname,
('.py', 'r', imp.PY_SOURCE))
f.close()
plugins = []
for dummy, member in inspect.getmembers(module, inspect.isclass):
if issubclass(member, Plugin):
p = member(*self.plugin_arguments,
**self.plugin_keyword_arguments)
if self.compatible_version(p.required_application_version):
plugins.append(p)
return plugins
The other way to do it might be to use the builtin functions globals
, issubclass
, and isinstance
. 另一种方法可能是使用内置函数
globals
, issubclass
和isinstance
。
In recent versions of Django the django.db.models.loading
apparently no longer exists, but you can list the models of an app with : 在最新版本的Django中,
django.db.models.loading
显然不再存在,但是您可以使用以下命令列出应用程序的模型:
from django.apps import apps
app = apps.get_app_config("your_app_name")
models = app.get_models()
for model in models:
print(model)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.