一、默認參數
python為了簡化函數的調用,提供了默認參數機制:
def pow(x, n = 2): r = 1 while n > 0: r *= x n -= 1 return r
這樣在調用pow函數時,就可以省略最后一個參數不寫:
print(pow(5)) # output: 25
在定義有默認參數的函數時,需要注意以下:
必選參數必須在前面,默認參數在后;
設置何種參數為默認參數?一般來說,將參數值變化小的設置為默認參數。
python標準庫實踐
python內建函數:
print(*objects, sep=' ', end='/n', file=sys.stdout, flush=False)
函數簽名可以看出,使用print('hello python')這樣的簡單調用的打印語句,實際上傳入了許多默認值,默認參數使得函數的調用變得非常簡單。
二、出錯了的默認參數
引用一個官方的經典示例地址 :
def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_listprint(bad_append('1'))print(bad_append('2'))這個示例并沒有按照預期打印:
['1']['2']
而是打印了:
['1']['1', '2']
其實這個錯誤問題不在默認參數上,而是我們對于及默認參數的初始化的理解有誤。
三、默認參數初始化
實際上,默認參數的值只在定義時計算一次,因此每次使用默認參數調用函數時,得到的默認參數值是相同的。
我們以一個直觀的例子來說明:
import datetime as dtfrom time import sleepdef log_time(msg, time=dt.datetime.now()): sleep(1) # 線程暫停一秒 print("%s: %s" % (time.isoformat(), msg))log_time('msg 1')log_time('msg 2')log_time('msg 3')運行這個程序,得到的輸出是:
2017-05-17T12:23:46.327258: msg 12017-05-17T12:23:46.327258: msg 22017-05-17T12:23:46.327258: msg 3
即使使用了sleep(1)讓線程暫停一秒,排除了程序執行很快的因素。輸出中三次調用打印出的時間還是相同的,即三次調用中默認參數time的值是相同的。
上面的示例或許還不能完全說明問題,以下通過觀察默認參數的內存地址的方式來說明。
首先需要了解內建函數id(object) :
id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.
即id(object)函數返回一個對象的唯一標識。這個標識是一個在對象的生命周期期間保證唯一并且不變的整數。在重疊的生命周期中,兩個對象可能有相同的id值。
在CPython解釋器實現中,id(object)的值為對象的內存地址。            
新聞熱點
疑難解答