我有一些模块位于不同的目录中。只有当这些类是ParentClass
的子类时,我如何在这些module
中实例化类?从本质上讲,我想是这样的下面,想知道怎样才能实现child_class_name
实例化来自不同目录的Python子类
from importlib.machinery import SourceFileLoader
from parent_class import ParentClass
instances = []
script_path1 = r'/some/different/directory/some_child.py'
script_path2 = r'/some/different/directory/another_child.py'
for script_path in [script_path1, script_path2]:
module = SourceFileLoader('module', script_path).load_module()
child_class_name = "If a class in this module is a subclass of ParentClass"
ChildClass = getattr(module, child_class_name)
instances.append(ChildClass())
我不明白你需要什么确切地说,如何检查'ChildClass'是否是一个子类?或循环遍历模块中的所有类对象以查找哪一个是子类? – PRMoureu
后者循环遍历模块中的所有类对象以找到哪一个是子类,以便我可以创建'ChildClass'谢谢! –