你能阻止函数在python中的字典映射中执行吗?

时间:2016-02-22 10:18:09

标签: python function dictionary

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

def testfunc():
    print 'Executed'

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

如果没有,有更好的方法吗?这会是对装饰者的要求吗?

3 个答案:

答案 0 :(得分:2)

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

testdict = {'1': testfunc,}

答案 1 :(得分:1)

简单地说,在映射时删除函数名称后面的括号:

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

&安培;称之为:

testdict['1']()

答案 2 :(得分:1)

是的,您可以通过不提供括号来禁止执行pf方法,而不是调用它,menas。 无论何时您想调用方法,请参阅下文:

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