如何在Python中动态选择方法调用?

时间:2011-11-15 18:23:23

标签: 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

5 个答案:

答案 0 :(得分:6)

使用getattr并调用其结果:

getattr(foo_obj, command)()

将其视为:

method = getattr(foo_obj, command)
method()

但是当然,从用户输入中获取command字符串时要小心。您最好检查是否允许使用类似

的命令
command in {'print', 'install', 'remove'}

答案 1 :(得分:5)

self.command_table = {"print":self.print, "install":self.install, "remove":self.remove}

def function(self, command):
    self.command_table[command]()

答案 2 :(得分:3)

创建一个dict,将命令映射到方法调用:

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

答案 3 :(得分: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()    

答案 4 :(得分:2)

functions = {"print": foo_obj.print,
             "install": foo_obj.install,
             "remove": foo_obj.remove}
functions[command]()