1. 程式人生 > >Python中預設引數值

Python中預設引數值

關於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)))
f(2) # 函式被呼叫,會從初始化義讀取I值,並且更改I值f(2,[3,2,1]) # 函式重新呼叫,I引數被賦值f(3) # 函式重新呼叫,雖然在函式體內I被重新賦值為空[],但是呼叫I的值是在初始化的定義的值程式執行前I的值為: []
I id is : 42474792 
程式執行前I的值為: [3, 2, 1]
I id is : 42474872 
程式執行前I的值為: [0, 1]
I id is : 42474792