2014-01-25 40 views
3

我的代碼是這樣的:爲什麼Python中的函數字典自動執行自己?

def quick(): 
    print "dex is 1" 

def strong(): 
    print "str is 1" 

def start(): 
    suffix = {"quick" : quick(), "strong" : strong()} 
    suffix.get("quick") 

start() 

然後我執行這個文件。結果變成:

dex is 1 
str is 1 

看來我的dict.get()在這裏工作不好,爲什麼?如何解決它?

回答

2

你必須使用功能的一個變量,在你的字典,並只在需要時撥打電話:

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()

2

因爲有()函數名後。函數調用的返回值用於字典值而不是函數。

def start(): 
    suffix = {"quick" : quick(), "strong" : strong()} 
    #      ^^     ^^ 

修復:

def start(): 
    suffix = {"quick" : quick, "strong" : strong} # Use function itself. 
    func = suffix.get("quick") # Get function object. 
    func()      # Call it. 
2

時候你寫

suffix = {"quick" : quick(), "strong" : strong()} 

功能quick()strong()越來越執行。你需要改變,要

suffix = {"quick" : quick, "strong" : strong} 

,並呼籲他們爲:

suffix["quick"]() 

這是蟒蛇一個很酷的功能。如果你想通過你的函數quick(),你可以通過它們作爲

suffix["quick"](<arguments>) 
相關問題