Turn string into function call

Gerhard Häring gh_pythonlist at gmx.de
Fri Mar 8 10:35:47 EST 2002


Le 08/03/02 à 05:45, N Becker écrivit:
> What's the best way to turn a string naming a function into a function call?
 
Use a dictionary that maps your commands to the relevant functions, then
call the function using the dictionary. This gives the idea (hopefully):

def command1func(): print "a"
def command2func(): print "b"
commands = {'command1': command1func, 'command2': command2func}

curcmd = 'command1'
if curcmd in commands.keys():
    commands['command1']()
else:
    print "illegal command"

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 10.6 °C      Wind: 2.9 m/s




More information about the Python-list mailing list