나는 다음과 같은 것을 시도하고 있습니다.
from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U
objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...
위의 코드는 매우 커서 새 클래스 나 모듈을 추가 할 때마다 업데이트하는 데 불필요한 시간이 많이 걸립니다. 대신 디렉토리 내의 각 클래스와 모든 중첩 된 디렉토리에서 객체를 동적으로 초기화하는 방법을 원합니다. 다음으로 요약되는 것.
objs = []
for py_file in directory:
for class in py_file:
objs.append(construct_object_of_type(class))
참고로 이러한 모든 클래스는 단일 기본 클래스에서 상속됩니다. 이 코드는 최상위 디렉토리의 python 파일에서도 호출됩니다.
그래서 나는 이것을하는 방법을 알아 냈다.
이에 대한 코드는 다음과 같습니다.
import os
import imp
import inspect
obj_list = []
dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"
for path, subdirs, files in os.walk(dir_path):
for name in files:
if fnmatch(name, pattern):
found_module = imp.find_module(name[:-3], [path])
module = imp.load_module(name, found_module[0], found_module[1], found_module[2])
for mem_name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and inspect.getmodule(obj) is module:
obj_list.append(obj())
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다