2017-10-13 1 views
1

다른 디렉토리에있는 모듈이 있습니다. 클래스가 서브 클래스가 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()) 
+1

난 당신이 필요로하는 것을 이해하지 못했다 'ChildClass'가 하위 클래스인지 확인하는 방법은 무엇입니까? 어떤 클래스가 하위 클래스인지 찾기 위해 모듈의 모든 클래스 객체를 반복합니다. – PRMoureu

+0

후자는 모듈의 모든 클래스 객체를 반복하여 어느 클래스가 하위 클래스인지 찾아서'ChildClass'를 만들 수 있습니다. Thanks! –

답변

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

편집 :

,210

은 세트에 목록을 변환 할 수 있습니다 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 ] 
+1

이것은 아름다운 해결책입니다! 한가지 질문은,'[, ]'처럼'childclasses'에서'ParentClass'를 어떻게 제거 할 수 있습니까? 왜냐하면 각 자식 모듈에는'parent_class import ParentClass'가 있기 때문입니다. –

관련 문제