calling variable function name ?

Duncan Booth duncan.booth at invalid.invalid
Thu May 1 03:59:35 EDT 2008


"thinkofwhy" <thinkofwhy at yahoo.ca> wrote:

> Try a dictionary:
> 
>     def funcA(blah, blah)
>     def funcB(blah, blah)
>     def funcC(blah, blah)
>     functions = {'A': funcA, 'B': funcB, 'C': 
> funcC}
>     user_func = 'A'
>     functions[user_func] #execute function

Python has a neat concept for making this easy :^) it is called a class.

class MyFunctions(object):
    def funcA(self, param1, param2):
    	  print "FA " + param1 + " " + param2

    def funcB(self, param1, param2):
    	  print "FB " + param1 + " " + param2

    def funcC(self, param1, param2):
    	  print "FC " + param1 + " " + param2

    def defaultFunc(self, *args):
        print "Command not recognised"

    def doCommand(self, cmd, *args):
        return getattr(self, 'func'+cmd, self.defaultFunc)(*args)

functions = MyFunctions()
result = functions.doCommand('A', 'foo', 'bar')

You have to add an extra 'self' argument to each function (or make it a 
staticmethod), but you could always use it to store state without resorting 
to globals.



More information about the Python-list mailing list