2011-08-24 8 views
2

제 질문은 this one과 비슷합니다.모듈을 동적으로 가져오고 파이썬에서 클래스를 인스턴스화하십시오.

매개 변수와 함께 여러 작업을 이름으로 호출하는 구성 파일을 구문 분석하고 있습니다. 예를 들어 :

"on_click": "action1", "args": {"rate": 1.5} 

조치 파이썬 클래스는 기본 Action 클래스에서 상속, 그리고 명명 된 인수를 취할 수 있습니다. 그것들은 프로젝트의 'actions'서브 디렉토리에 저장되며, 접두사는 a_입니다. 다른 파일을 변경하지 않고 새 파일을 간단히 삭제하여 새로운 작업을 추가하고 싶습니다. 프로젝트 구조는 다음과 같다 :

myapp/ 
    actions/ 
     __init__.py 
     baseaction.py 
     a_pretty.py 
     a_ugly.py 
     ... 
    run.py 

모든 액션 클래스가 PerformAction() 방법과 구성 파일에 의미 무엇입니까 GetName() 방법을 제공한다. 이 예에서 a_pretty.pyPrettyPrinter이라는 클래스를 정의합니다. GetName()PrettyPrinter에 붙이면 "action1"이 반환됩니다.

나는 키와 "조치 1"과 사전에 PrettyPrinter 클래스를 추가하고 싶습니다, 그래서 다음과 같이 그것의 새로운 인스턴스를 인스턴스화 할 수 있습니다 : 현재

args = {'rate': the_rate} 
instantiated_action = actions['action1'](**args) 
instantiated_action.PerformAction() 

, 나는 다음 있습니다 :

actions = [os.path.splitext(f)[0] for f in os.listdir("actions") 
      if f.startswith("a_") and f.endswith(".py")] 

for a in actions: 

    try: 
     module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"]) 
     # What goes here? 
    except ImportError: 
     pass 

은 작업 파일을 가져 오는, 나는 dir(module)를 인쇄하면 내가 클래스 이름을 참조; 나는 단지 다음에해야 할 일이 무엇인지 알지 못한다. (또는이 모든 접근법이 올바른 방향으로 나아갈 수 있다면 ...).

답변

2

만약에 모든 것을 module 당신이 실체화 같은 것을 시도해야 클래스입니다 : 행동에 대한

을 :

try: 
    module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"]) 
    # What goes here? 
    # let's try to grab and instanciate objects 
    for item_name in dir(module): 
     try: 
      new_action = getattr(module, item_name)() 
      # here we have a new_action that is the instanciated class, do what you want with ;) 
     except: 
      pass 

except ImportError: 
    pass 
+0

감사합니다; 나는'getattr' 사용을 생각하지 않았습니다. – Rezzie

관련 문제