简体   繁体   English

您可以阻止函数在python的字典映射中执行吗?

[英]Can you prevent a function from executing inside a dictionary mapping in python?

When mapping functions to a dictionary, python automatically executes the function before the key is called. 将函数映射到字典时,python会在调用键之前自动执行该函数。 Can this be prevented? 可以预防吗? Example: 例:

def testfunc():
    print 'Executed'

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

If not, is there a better way to do this? 如果没有,还有更好的方法吗? Would this be a call for decorators or something? 这将是对装饰的呼吁吗?

The way you are creating the dictionary maps the return value of testfunc() to the key '1' . 创建字典的方式会将testfunc()的返回值映射到键'1' In order to know the return value, the function has to be executed first. 为了知道返回值,必须首先执行该函数。 If you are simply trying to save the function in the dictionary, do: 如果您只是想将函数保存在字典中,请执行以下操作:

testdict = {'1': testfunc,}

Simply, remove the parentheses after the function's name when mapping: 只需在映射时删除函数名称后的括号即可:

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

& to call it: &称之为:

testdict['1']()

Yes, you may prevent the execution pf method, by not calling it,menas by not providing the parentheses. 是的,可以通过不调用pf方法来阻止执行pf方法,也可以通过不提供括号来防止执行方法。 And whenever you want to call the method you can,see below: 每当您想调用该方法时,请参见以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM