2011-11-15 66 views
4

我有一個類似的代碼:如何在Python中動態選擇方法調用?

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

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

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

command是一個字符串(我通過解析命令行參數定義它,但是這超出了點)。有沒有辦法用類似這樣的代碼替換上面的代碼塊?

foo_obj.function(command) 

對於我條記錄我使用Python 2.7

回答

3

的核心功能可以是:

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

當然,你應該只允許某些方法:

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

使用getattr並調用它的結果:

getattr(foo_obj, command)() 

讀取爲:

method = getattr(foo_obj, command) 
method() 

當然但是,要從用戶輸入中獲取command字符串時要小心。你最好檢查命令是否被允許的東西,如

command in {'print', 'install', 'remove'} 
+2

每隔答案是不如這一次,我們沒有理由創造額外的簿記當Python有反射! – Aphex

3

創建一個字典映射命令來調用方法:

commands = {"print": foo_obj.print, "install": foo_obj.install} 
commands[command]() 
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]() 
相關問題