如何使用用户输入在Python中调用函数?

Isa*_*ins 6 python function

我有几个功能,如:

def func1():
    print 'func1'

def func2():
    print 'func2'

def func3():
    print 'func3'
Run Code Online (Sandbox Code Playgroud)

然后我要求用户输入他们想要运行choice = raw_input()的功能,并尝试调用他们使用的功能choice().如果用户输入func1而不是调用该函数,则会给出一个错误'str' object is not callable.无论如何,他们是否将"选择"转变为可赎回价值?

Gri*_*han 8

错误是因为函数名不是字符串你不能调用'func1'()它应该是的函数func1(),

你可以这样做:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice)()
Run Code Online (Sandbox Code Playgroud)

它通过将字符串映射到函数引用

旁注:你可以写一个默认函数,如:

def notAfun():
  print "not a valid function name"
Run Code Online (Sandbox Code Playgroud)

并改善你的代码:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice, notAfun)()
Run Code Online (Sandbox Code Playgroud)


Ale*_*yev 1

您可以使用locals

>>> def func1():
...     print 'func1 - call'
... 
>>> def func2():
...     print 'func2 - call'
... 
>>> def func3():
...     print 'func3 - call'
... 
>>> choice = raw_input()
func1
>>> locals()[choice]()
func1 - call
Run Code Online (Sandbox Code Playgroud)