Python对调用func和语法表示怀疑
我完全是个新手,即使我还在阅读python文档,我也会对语法产生疑问 我在我的.py中有我的函数Python对调用func和语法表示怀疑,python,function,logic,Python,Function,Logic,我完全是个新手,即使我还在阅读python文档,我也会对语法产生疑问 我在我的.py中有我的函数 def f1: pass def f2: pass def f3: pass 因此,我想选择一个数字来调用如下函数: a = input('Insert the function number') “f$d”(%a)#我尝试过类似的东西,完全奇怪,但我是新手(有点愚蠢) 如果这是一个愚蠢的问题,很抱歉,但我不知道如何才能做到。你可以很容易地做到这一点。列出您的功能: list_
def f1:
pass
def f2:
pass
def f3:
pass
因此,我想选择一个数字来调用如下函数:
a = input('Insert the function number')
“f$d”(%a)#我尝试过类似的东西,完全奇怪,但我是新手(有点愚蠢)
如果这是一个愚蠢的问题,很抱歉,但我不知道如何才能做到。你可以很容易地做到这一点。列出您的功能:
list_func = [f1, f2, f3]
globals()['f%d'%inp]()
和第次执行:
a = int(input('insert the function number: ') #get the input and convert it to integer
list_func[a]() #execute the function inputted
或不带列表功能:
inp = int(input('insert the function number: ') #get the input and convert it to integer
eval('f%d'%inp)
请记住,不要经常使用eval()
。这有点不安全
或者,您可以从globals()
调用它,它能够返回全局变量和函数的字典:
list_func = [f1, f2, f3]
globals()['f%d'%inp]()
不,就这样。
希望这有帮助 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
旁白:Python语法要求即使不带参数的函数也在其定义中使用括号。注意,它必须是
def f1():pass
等。你说的“描述我的函数”是什么意思?list_func
是否包含函数名?