How To Dynamically Select A Method Call?
I have a code similar to this: if command == 'print': foo_obj.print() if command == 'install': foo_obj.install() if command == 'remove': foo_obj.remove() command
Solution 1:
Use getattr
and call its result:
getattr(foo_obj, command)()
Read that as:
method= getattr(foo_obj, command)
method()
But of course, be careful when taking the command
string from user input. You'd better check whether the command is allowed with something like
commandin {'print', 'install', 'remove'}
Solution 2:
self.command_table = {"print":self.print, "install":self.install, "remove":self.remove}
def function(self, command):
self.command_table[command]()
Solution 3:
The core function may be as:
fn = getattr(foo_obj, str_command, None)
ifcallable(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)
assertcallable(fn), "Command '%s' is invalid"%str_command
#Ok, call it!
fn()
Solution 4:
Create a dict mapping the commands to the method call:
commands = {"print": foo_obj.print, "install": foo_obj.install}
commands[command]()
Solution 5:
functions = {"print": foo_obj.print,
"install": foo_obj.install,
"remove": foo_obj.remove}
functions[command]()
Post a Comment for "How To Dynamically Select A Method Call?"