从不同目录实例化Python子类

时间:2017-10-13 15:43:53

标签: python python-3.x module subclass

我有一些位于不同目录中的模块。只有当类是module的子类时,如何才能在这些ParentClass中实例化类?从本质上讲,我正在尝试下面这样的事情,并想知道如何实现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())

1 个答案:

答案 0 :(得分:2)

这应该适用于这个理解列表:

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 ]
相关问题