Python中預設引數值
阿新 • • 發佈:2019-02-04
關於Python預設引數,假如預設引數是可變(mutable)物件是會有副作用的,一個函式引數的預設值,僅僅在該函式定義的時候,被賦值一次。如此,只有當函式第一次被定義的時候,才將引數的預設值初始化到它的預設值(如一個空的列表)
如:
>>> def function(data=[]): data.append(1) return data >>> function() [1] >>> function() [1, 1] >>> function() [1, 1, 1]
當def function(data=[])執行完成,預先計算的值,即data就會被每次函式呼叫所使用,尤其是當預設引數是可變的物件時,引數可以"類比為全域性變數,當然這個全域性變數的範圍是在函式範圍內的"
引用其他博文所說:“
“Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same ``pre-computed'' value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None
as the default, and explicitly test for it in the body of the function
def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin
def f(x, I=[]): # 函式初始化定義,I僅僅被賦值一次 print('程式執行前I的值為: {}'.format(I)) for i in range(x): I.append(i*i) print('I id is : {} '.format(id(I)))
I id is : 42474792
程式執行前I的值為: [3, 2, 1]
I id is : 42474872
程式執行前I的值為: [0, 1]
I id is : 42474792