从不同的目录实例化Python子类

2024-04-20 11:16:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些在不同目录中的模块。仅当类是ParentClass的子类时,如何实例化这些module中的类?基本上,我正在尝试下面这样的东西,想知道如何实现child_class_name

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())

Tags: instancesnamefrompyimportchildscriptsome
1条回答
网友
1楼 · 发布于 2024-04-20 11:16:31

这应该适用于以下理解列表:

childclasses = [obj for obj in vars(module).values() 
                   if isinstance(obj,type) and issubclass(obj,ParentClass)]

vars(module).values()返回模块中的所有对象。你知道吗

然后可以用issubclass(obj,ParentClass)过滤子类。你知道吗

isinstance只会帮助过滤类对象。)


childclasses是可以直接实例化的类列表,无需使用getattr

for ChildClass in childclasses:
    instances.append(ChildClass())

编辑:

为了避免ParentClass,您可以将列表转换为一个集合,如果存在则将其删除:

childclasses = set([obj for obj in vars(module).values() 
                       if isinstance(obj,type) and issubclass(obj,ParentClass)])
if ParentClass in childclasses:
    childclasses.remove(ParentClass)

或在理解中增加另一项测试:

childclasses = [obj for obj in vars(module).values() 
                       if isinstance(obj,type) and
                       issubclass(obj,ParentClass)and 
                       obj is not ParentClass ]

相关问题 更多 >