【问题标题】:Can you prevent a function from executing inside a dictionary mapping in python?你能阻止函数在 python 的字典映射中执行吗?
【发布时间】:2016-02-22 10:18:08
【问题描述】:

将函数映射到字典时,python 会在调用键之前自动执行函数。这可以防止吗? 示例:

def testfunc():
    print 'Executed'

testdict = { '1': testfunc(),}
>>>EXECUTED

如果没有,有没有更好的方法来做到这一点?这会是对装饰师的要求吗?

【问题讨论】:

  • 省略函数调用运算符(),所以'1': testfunc

标签: python function dictionary


【解决方案1】:

您创建字典的方式将testfunc() 的返回值映射到键'1'。为了知道返回值,必须先执行该函数。如果您只是想将函数保存在字典中,请执行以下操作:

testdict = {'1': testfunc,}

【讨论】:

    【解决方案2】:

    是的,您可以通过不调用 pf 方法来阻止执行 pf 方法,或者通过不提供括号来阻止它。 并且无论何时您想调用该方法都可以,请参见下文:

    def testfunc():
        print 'Executed'
    testdict = {'1': testfunc,}
    testdict['1']()
    Executed
    

    【讨论】:

      【解决方案3】:

      简单地说,映射时去掉函数名后面的括号:

      testdict = {'1': testfunc,} # remove the parentheses, in order to save the function, 
                                  # not its return value
      

      & 来称呼它:

      testdict['1']()
      

      【讨论】:

      • 如果您想通过函数传递参数,您将如何处理?
      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 2021-12-14
      • 2017-06-11
      • 2015-02-05
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      相关资源
      最近更新 更多