Python 为什么我的函数会自动执行?
我有一个dict,它存储两个类似的函数:Python 为什么我的函数会自动执行?,python,function,dictionary,function-call,Python,Function,Dictionary,Function Call,我有一个dict,它存储两个类似的函数: def quick(): print("dex is 1") def strong(): print("str is 1") def start(): suffix = {"quick" : quick(), "strong" : strong()} suffix.get("quick") start() suffix = {"quick": None, "strong": None} 然后我执行这个代码,输出是
def quick():
print("dex is 1")
def strong():
print("str is 1")
def start():
suffix = {"quick" : quick(), "strong" : strong()}
suffix.get("quick")
start()
suffix = {"quick": None, "strong": None}
然后我执行这个代码,输出是:
dex is 1
str is 1
似乎我的
dict.get()
在这里工作不太好。为什么要执行这两个函数,而不仅仅是quick
函数?您必须在dict中将函数用作变量,并且仅在需要时进行调用:
def quick():
print("dex is 1")
def strong():
print("str is 1")
def start():
# without a `()` after a function's name, the function is just a variable,
# waiting for a call
suffix = {"quick" : quick, "strong" : strong}
suffix.get("quick")() # and here is the actual call to the function
start()
因为函数名后面有()
。函数调用的返回值用于字典值,而不是函数
def start():
suffix = {"quick" : quick(), "strong" : strong()}
# ^^ ^^
修正:
当你写作的时候
suffix = {"quick" : quick(), "strong" : strong()}
正在执行函数quick()
和strong()
。你需要把它改成
suffix = {"quick" : quick, "strong" : strong}
并称之为:
suffix["quick"]()
这是python中一个很酷的特性。如果要将参数传递给函数quick()
,可以将其作为
suffix["quick"](<arguments>)
后缀[“快速”]()
问题在于,您没有在dict中存储函数,而是存储这些函数的返回值:当您编写quick()
时,您正在调用函数。你的口述最后看起来是这样的:
def quick():
print("dex is 1")
def strong():
print("str is 1")
def start():
suffix = {"quick" : quick(), "strong" : strong()}
suffix.get("quick")
start()
suffix = {"quick": None, "strong": None}
您要做的是将函数本身存储在dict中,如下所示:
suffix = {"quick": quick, "strong": strong} # no parentheses!
这将为您提供一个包含两个函数对象的dict。现在,您可以从dict中取出一个函数并调用它:
func = suffix.get("quick")
func()
就像那样,您的代码将正常工作
def start():
suffix = {"quick": quick, "strong": strong} # no parentheses!
func = suffix.get("quick")
func()
start() # output: dex is 1
如果需要将一些参数与dict中的函数相关联,请查看