Why do my functions automatically execute themselves?
我有一个dict存储两个这样的函数:
1 2 3 4 5 6 7 8 9 10 11 | def quick(): print("dex is 1") def strong(): print("str is 1") def start(): suffix = {"quick" : quick(),"strong" : strong()} suffix.get("quick") start() |
然后我执行这段代码,输出是:
1 2 | dex is 1 str is 1 |
看来我的
问题是你没有在dict中存储函数,而是存储这些函数的返回值:当你写
1 | suffix = {"quick": None,"strong": None} |
你想要做的是将函数本身存储在dict中,如下所示:
1 | suffix = {"quick": quick,"strong": strong} # no parentheses! |
这为你提供了一个内部有两个函数对象的dict。你现在可以从dict中取出一个函数并调用它:
1 2 | func = suffix.get("quick") func() |
就这样,您的代码将正常工作。
1 2 3 4 5 6 | def start(): suffix = {"quick": quick,"strong": strong} # no parentheses! func = suffix.get("quick") func() start() # output: dex is 1 |
如果需要将某些参数与dict中的函数关联,请查看此问题。
当你写作
1 | suffix = {"quick" : quick(),"strong" : strong()} |
函数
1 | suffix = {"quick" : quick,"strong" : strong} |
并称他们为:
1 | suffix["quick"]() |
这是python中的一个很酷的功能。如果你想将争论传递给你的函数
1 | suffix["quick"]() |
因为函数名后面有
1 2 3 | def start(): suffix = {"quick" : quick(),"strong" : strong()} # ^^ ^^ |
固定:
1 2 3 4 | def start(): suffix = {"quick" : quick,"strong" : strong} # Use function itself. func = suffix.get("quick") # Get function object. func() # Call it. |
您必须在dict中使用函数作为变量,并仅在需要时进行调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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() |