I have several functions such as:
def func1():
print 'func1'
def func2():
print 'func2'
def func3():
print 'func3'
Then I ask the user to input what function they want to run using choice = raw_input() and try to invoke the function they choose using choice(). If the user input func1 rather than invoking that function it gives me an error that says 'str' object is not callable. Is their anyway for me to turn 'choice' into a callable value?
解决方案
The error is because function names are not string you can't call function like 'func1'() it should be func1(),
You can do like:
{
'func1': func1,
'func2': func2,
'func3': func3,
}.get(choice)()
its by mapping string to function references
side note: you can write a default function like:
def notAfun():
print "not a valid function name"
and improve you code like:
{
'func1': func1,
'func2': func2,
'func3': func3,
}.get(choice, notAfun)()