Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For the recored I'm using Python 2.7

like image 726
rahmu Avatar asked Dec 02 '22 01:12

rahmu


1 Answers

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

command in {'print', 'install', 'remove'}
like image 73
Fred Foo Avatar answered Dec 04 '22 15:12

Fred Foo