Fire Method by predefined string!
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Nov 17 20:41:33 EST 2013
On Sun, 17 Nov 2013 17:20:52 -0500, Roy Smith wrote:
> In article <mailman.2807.1384725251.18130.python-list at python.org>,
> Tamer Higazi <th982a at googlemail.com> wrote:
>> I want the param which is a string to be converted, that I can fire
>> directly a method. Is it somehow possible in python, instead of writing
>> if else statements ???!
>
> I'm not sure why you'd want to do this, but it's certainly possible
It is very good for implementing the Command Dispatch pattern, which in
turn is very good for building little command interpreters or mini-
shells. Python even comes with a battery for that:
import cmd
import sys
class MyShell(cmd.Cmd):
# Override default behaviour of empty lines.
def emptyline(self):
pass
# Define commands for our shell by prefixing them with "do_".
def do_hello(self, person):
if person:
print("Hello, %s!" % person)
else:
print("Hello!")
def do_echo(self, line):
print(line)
def do_double(self, num):
print(2*float(num))
def do_bye(self, line):
return True
MyShell().cmdloop()
This defines and runs a command interpreter that understands commands
"bye", "double", "echo", "hello" and "help". (Help is predefined for you.)
See also http://drunkenpython.org/dispatcher-pattern-safety.html for
another use of command dispatch.
--
Steven
More information about the Python-list
mailing list