将模块中的所有类初始化为列表中的无名对象 [英] Initialize all the classes in a module into nameless objects in a list
问题描述
是否可以将python模块中的所有类初始化为无名对象列表?
Is there a way to initialize all classes from a python module into a list of nameless objects?
示例
我有一个模块rules
,其中包含类Rule中的所有子类.因此,我确定他们都将实现方法run()
并将具有属性name
,该属性将在调用__init__
Example
I have a module rules
which contains all child classes from a class Rule. Because of that, I'm certain they will all implement a method run()
and will have a attribute name
which will be generated during the call of __init__
我想要一个从这些类动态初始化的对象的列表.通过动态初始化,我的意思是它们不必显式命名.
I would like to have a list of objects dynamically initiated from those classes. By dynamically initialized i mean that they don't have to be named explicitly.
问题是:
是否可以遍历模块中的所有类?
Is it possible to iterate through all classes in a module?
可以启动无名对象吗?
推荐答案
您至少可以采用两种方法.您可以通过调用类的__subclasses__()
方法来获取类的所有子类.因此,如果您的父类称为Rule
,则可以调用:
There are at least two approaches you can take. You can get all of the subclasses of a class by calling a class's __subclasses__()
method. So if your parent class is called Rule
, you could call:
rule_list = [cls() for cls in Rule.__subclasses__()]
这将为您提供Rule
的所有子类,并且不会将它们限制为在特定模块中找到的子类.
This will give you all subclasses of Rule
, and will not limit them to the ones found in a particular module.
如果您有模块的句柄,则可以遍历其内容.像这样:
If you have a handle to your module, you can iterate over its content. Like so:
import rule
rule_list = []
for name in dir(rule):
value = getattr(rule, name)
if isinstance(value, type) and issubclass(value, Rule):
rule_list.append(value())
不幸的是,如果给它一个不是类的对象作为第一个参数,则issubclass
会抛出TypeError
.因此,您必须以某种方式处理该问题.
Unfortunately, issubclass
throws TypeError
if you give it an object that is not a class as its first argument. So you have to handle that somehow.
按照@Blckknght的建议处理issubclass
怪癖.
dealing with the issubclass
quirk per @Blckknght's suggestion.
这篇关于将模块中的所有类初始化为列表中的无名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!