2013-05-18 68 views
4

我有几个功能,如:如何使用用户输入来在Python中调用函数?

def func1(): 
    print 'func1' 

def func2(): 
    print 'func2' 

def func3(): 
    print 'func3' 

然后我问他们想用choice = raw_input()运行,并尝试调用他们选择使用choice()的功能是什么功能的用户输入。如果用户输入func1而不是调用该函数,它会给我一个错误,说'str' object is not callable。他们无论如何都会将“选择”变成可调用的价值吗?

回答

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 
+1

或更一般地说,OP的'globals' – shx2

6

这个错误是因为函数名不是你不能调用函数像'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)() 
+0

:它将是[**运行时多态性**]的示例(http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29#Subtype_polymorphism_。 28or_inclusion_polymorphism.29)!在Python –

3

如果你犯了一个更加复杂的程序它可能是简单的使用CMD来自Python标准库的模块,而不是写一些东西。
你的榜样会再看看这样:

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版本的更多信息。

+0

+惊人的!谢谢:) –

+0

+1 for cmdloop() –

相关问题