【问题标题】:Python Call Function from String [duplicate]来自字符串的Python调用函数[重复]
【发布时间】:2015-04-06 23:25:45
【问题描述】:
s = "func"

现在假设有一个名为 func 的函数。 当函数名以字符串形式给出时,如何在 Python 2.7 中调用 func?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    最安全的方法:

    In [492]: def fun():
       .....:     print("Yep, I was called")
       .....:
    
    In [493]: locals()['fun']()
    Yep, I was called
    

    根据上下文,您可能希望改用globals()

    或者,您可能想要这样设置:

    def spam():
        print("spam spam spam spam spam on eggs")
    
    def voom():
        print("four million volts")
    
    def flesh_wound():
        print("'Tis but a scratch")
    
    functions = {'spam': spam,
                 'voom': voom,
                 'something completely different': flesh_wound,
                 }
    
    try:
        functions[raw_input("What function should I call?")]()
    except KeyError:
        print("I'm sorry, I don't know that function")
    

    你也可以将参数传递给你的函数:

    def knights_who_say(saying):
        print("We are the knights who say {}".format(saying))
    
    functions['knights_who_say'] = knights_who_say
    
    function = raw_input("What is your function? ")
    if function == 'knights_who_say':
        saying = raw_input("What is your saying? ")
        functions[function](saying)
    else:
        functions[function]()
    

    【讨论】:

      【解决方案2】:

      你可以通过传递一个字符串来执行一个函数:

      exec(s + '()')
      

      【讨论】:

      • 这行不通,因为你从不调用函数
      • 是的,我明白了,它只会返回函数对象而不是调用它。我修好了。
      【解决方案3】:
      def func():
          print("hello")
      s = "func"
      eval(s)()
      
      In [7]: s = "func"
      
      In [8]: eval(s)()
      hello
      

      不推荐!只是告诉你如何做。

      【讨论】:

      • @BhargavRao,这是一个大胆的声明!
      • @MagentaNova,我很确定它确实如此
      • @padriac,你是对的,删除评论。
      【解决方案4】:

      你可以使用 exec。不推荐但可行。

      s = "func()"
      
      exec s 
      

      【讨论】:

        猜你喜欢
        • 2011-03-20
        • 1970-01-01
        • 2011-12-17
        • 2015-04-22
        • 2011-05-07
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多