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

2024-05-16 02:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个功能,例如:

def func1():
    print 'func1'

def func2():
    print 'func2'

def func3():
    print 'func3'

然后我要求用户输入他们想使用choice = raw_input()运行的函数,并尝试使用choice()调用他们选择的函数。如果用户输入func1而不是调用该函数,则会给我一个错误,显示为'str' object is not callable。对我来说,他们是不是要把“选择”变成一个可调用的值?


Tags: 函数用户功能inputrawobjectisdef
3条回答

您可以使用locals

>>> def func1():
...     print 'func1 - call'
... 
>>> def func2():
...     print 'func2 - call'
... 
>>> def func3():
...     print 'func3 - call'
... 
>>> choice = raw_input()
func1
>>> locals()[choice]()
func1 - call

如果您制作了一个更复杂的程序,那么使用Python标准库中的cmd模块可能比编写一些东西要简单得多。
你的例子看起来是这样的:

import cmd

class example(cmd.Cmd):
    prompt  = '<input> '

    def do_func1(self, arg):
        print 'func1 - call'

    def do_func2(self, arg):
        print 'func2 - call'

    def do_func3(self, arg):
        print 'func3 - call'

example().cmdloop()

一个例子是:

<input> func1
func1 - call
<input> func2
func2 - call
<input> func3
func3 - call
<input> func
*** Unknown syntax: func
<input> help

Undocumented commands:
======================
func1  func2  func3  help

使用此模块时,当用户输入不带do_的名称时,将调用名为do_*的每个函数。此外,将自动生成帮助,您可以向函数传递参数。

有关这方面的更多信息,请查看Python手册(here)或Python 3版本的手册(例如,here)。

错误是因为函数名不是字符串,不能像'func1'()那样调用函数,应该是func1()

你可以这样做:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice)()

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

旁注:您可以编写如下默认函数:

def notAfun():
  print "not a valid function name"

改进你的代码,比如:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice, notAfun)()

相关问题 更多 >