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
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With