我是新手,即使我还在阅读python文档,我也会对语法产生怀疑。
我在my.py中有我的功能
def f1:
pass
def f2:
pass
def f3:
pass
所以我想选择一个数字来调用类似的函数:
a = input('Insert the function number')
“f $ d”()%##尝试了类似的东西,非常奇怪,但我是新手(有点傻)。
对不起,如果这是一个愚蠢的问题,但我不知道如何才能做到。
答案 0 :(得分:1)
你可以很容易地实现这一目标。列出您的功能:
list_func = [f1, f2, f3]
执行:
a = int(input('insert the function number: ') #get the input and convert it to integer
list_func[a]() #execute the function inputted
或没有list_func:
inp = int(input('insert the function number: ') #get the input and convert it to integer
eval('f%d'%inp)
请注意,请勿经常使用eval()
。这有点不安全。
或者,您可以从globals()
调用它,它可以返回全局变量和函数的字典:
globals()['f%d'%inp]()
不,那是关于它的。
希望这有帮助!
答案 1 :(得分:1)
Python的函数是标准对象,如整数,字符串,列表等。将任意键(名称,数字等)映射到对象以便按键查找对象的规范方法是使用dict
。所以:
def func1():
print "func1"
def func2():
print "func1"
def func3():
print "func1"
functions = {
"key1": func1,
"key2": func2,
"key3": func3,
}
while True:
key = raw_input("type the key or 'Q' to quit:")
if key in functions:
# get the function
f = functions[key]
# and call it:
f()
elif key == "Q":
break
else:
print "unknown key '%s'" % key