2016-05-17 67 views
0

您能否請某人描述Python可選參數在函數中的行爲?Python 3.5函數中的可選參數

我的理解是,可選參數在函數定義中使用默認值。

以下代碼具有正確的行爲。

# Function 
def testf2(val=0): 
    val += 5 
    print(val) 
    val=0 
    return 

# Testing 
testf2() 
testf2(10) 
testf2() 

# Output: 
5 
15 
5 

但我不知道爲什麼類似的代碼與可選列表有完全不同的行爲。即使列表被val = []清除,該函數也會記住一些數據。

# Function 
def testf(val=[]): 
    val.append("OK") 
    print(val) 
    val=[] 
    return 

# Testing 
testf() 
testf(["myString"]) 
testf() 
testf(["mySecondString"]) 
testf() 


# Output: 
['OK']      #excpected ['OK'] 
['myString', 'OK']   #excpected ['myString'] 
['OK', 'OK']    #excpected ['OK'] 
['mySecondString', 'OK'] #excpected ['mySecondString'] 
['OK', 'OK', 'OK']   #excpected ['OK'] 

非常感謝您的幫助。

回答

1

當定義函數時,Python的默認參數會被計算一次,而不是每次函數被調用。這意味着如果您使用可變默認參數並對其進行變異,那麼您將會爲該函數的所有將來調用突變該對象。

The Hitchhiker's Guide to Python: Common Gotchas