【问题标题】:Python doubts about calling func and SyntaxPython关于调用func和Syntax的疑惑
【发布时间】:2013-10-07 14:06:37
【问题描述】:

我完全是新手,即使我还在阅读 python 文档,但我对语法有疑问。

我的函数在 my.py 中

def f1:
  pass

def f2:
  pass

def f3:
  pass

所以我想选择一个数字来调用这样的函数:

a = input('Insert the function number') 

"f$d"() %a #我试过这样的东西,很奇怪,但我是新手(有点笨)。

对不起,如果这是一个愚蠢的问题,但我不知道我该怎么做。

【问题讨论】:

  • 旁白:Python 语法要求即使是不带参数的函数也必须在其定义中加上括号。 IOW,它必须是 def f1(): pass 等。
  • “描述我的功能”是什么意思? list_func 是否包含函数名称?

标签: python function logic


【解决方案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]()

不,就是这样。 希望这会有所帮助!

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2022-01-21
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多