代码之家  ›  专栏  ›  技术社区  ›  E.K.

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

  •  1
  • E.K.  · 技术社区  · 7 年前

    我有一些在不同目录中的模块。如何实例化这些中的类 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 回复  |  直到 7 年前
        1
  •  2
  •   PRMoureu    7 年前

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

    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 ]