Fire Method by predefined string!

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Nov 18 03:29:52 CET 2013


On 18/11/2013 01:41, Steven D'Aprano wrote:
> 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.
>

Neat, and yet another Python site to add to my list to keep an eye on, 
thanks.

-- 
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence




More information about the Python-list mailing list