2011-11-15 2 views
4

나는이 유사한 코드가 있습니다파이썬에서 동적으로 메서드 호출을 선택하는 방법은 무엇입니까?

if command == "print": 
    foo_obj.print() 

if command == "install": 
    foo_obj.install() 

if command == "remove": 
    foo_obj.remove() 

command는 문자열 (내가 명령 줄 인수를 구문 분석하여 정의를하지만, 그 지점을 넘어이다). 위의 코드를 이와 비슷한 것으로 대체하는 방법이 있습니까? 대한

foo_obj.function(command) 

의 I 그 결과 파이썬 2.7

답변

3

가 핵심 기능으로 할 수있다 : 당신은 더 나은 명령이 메소드 호출에 명령을 매핑 사전인가를 만들기

command in {'print', 'install', 'remove'} 
6

사용 getattr를 사용하여 전화를하고있어 간격의 저장 :

getattr(foo_obj, command)() 

읽기 같은 것을 :

method = getattr(foo_obj, command) 
method() 

그러나 물론, 일을 사용자 입력에서 command 문자열을 가져갈 때주의하십시오.

commands = {"print": foo_obj.print, "install": foo_obj.install} 
commands[command]() 
+2

마다 다른 대답이 하나의 열등는 파이썬이 반사가있는 경우 별도의 회계 장부를 만들 이유가 없습니다! – Aphex

3

처럼 뭔가 수 있는지 여부를 확인할 것

fn = getattr(foo_obj, str_command, None) 
if callable(fn): 
    fn() 

물론 특정 방법 만 허용해야합니다.

,210
str_command = ... 

#Double-check: only allowed methods and foo_obj must have it! 
allowed_commands = ['print', 'install', 'remove'] 
assert str_command in allowed_commands, "Command '%s' is not allowed"%str_command 

fn = getattr(foo_obj, str_command, None) 
assert callable(fn), "Command '%s' is invalid"%str_command 

#Ok, call it! 
fn()  
2
functions = {"print": foo_obj.print, 
      "install": foo_obj.install, 
      "remove": foo_obj.remove} 
functions[command]() 
5
self.command_table = {"print":self.print, "install":self.install, "remove":self.remove} 

def function(self, command): 
    self.command_table[command]() 
관련 문제