如何动态选择一个方法调用? [英] How to dynamically select a method call?
本文介绍了如何动态选择一个方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的代码:
if command == "print":
foo_obj.print()
if command == "install":
foo_obj.install()
if command == "remove":
foo_obj.remove()
command
是一个字符串(我通过解析命令行参数来定义它,但这已经超出了重点).有没有办法用类似的东西替换上面的代码?
command
is a string (I define it by parsing command line arguments, but that's beyond the point). Is there a way to replace the above chunck of code with something similar to this?
foo_obj.function(command)
对于重新录制的内容,我使用的是 Python 2.7
For the recored I'm using Python 2.7
推荐答案
核心功能可能为:
fn = getattr(foo_obj, str_command, None)
if callable(fn):
fn()
当然,您应该只允许某些方法:
Of course, you should allow only certain methods:
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()
这篇关于如何动态选择一个方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文