다른 디렉토리에있는 모듈이 있습니다. 클래스가 서브 클래스가 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())
난 당신이 필요로하는 것을 이해하지 못했다 'ChildClass'가 하위 클래스인지 확인하는 방법은 무엇입니까? 어떤 클래스가 하위 클래스인지 찾기 위해 모듈의 모든 클래스 객체를 반복합니다. – PRMoureu
후자는 모듈의 모든 클래스 객체를 반복하여 어느 클래스가 하위 클래스인지 찾아서'ChildClass'를 만들 수 있습니다. Thanks! –