Python 默認參數(注意事項!!!)

Tips

這篇文章會介紹在使用Python的默認參數時需要注意的事情。

什麼是默認參數?

從下面的範例代碼來解釋的話,默認參數是:date=datetime.now()

import time
frome datetime import datetime

def show_Second(date=datetime.now()):
  print(date.second)

Python的默認參數的陷阱!

讓我們執行剛剛的show_Second()函數,等待五秒後在使用一次show_Second()函數。

import time
frome datetime import datetime

def show_Second(date=datetime.now()):
  print(date.second)

show_Second()  # 15
time.sleep(5)  
show_Second()  # 15

這時候你會發現,明明已經用time.sleep(5)讓時間過去五秒鐘了,第二次的show_Second()顯示的還是跟五秒前相同的時間!???時間停止了嗎!!?The New World!!!????

Python的默認參數

看了一下Python的官方說明之後,發現裡面寫著下面的內容。

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call

from: https://docs.python.org/3/reference/compound_stmts.html#function-definitions

簡單的說明的話就是,在定義函數的時候默認參數將會被執行一次,並且將結果儲存在記憶體裡,之後不管使用這個函數幾次,只要使用了默認參數的話你所得到的結果都會是已經被儲存在記憶體中的結果。

因此,在使用例如datetime.now()這種每次結果都不同的函數的時候,使用默認參數是很危險的一件事!

Python的默認參數的對策

為了解決這個問題,可以將默認參數值設定為None,只要將None設定為默認參數的話接著就可以代入想要代入的值了!

下面是範例代碼。

import time
frome datetime import datetime

def show_Second(date=None):
  if date is None:
    date = datetime.now()
  print(date.second)

show_Second()  # 15
time.sleep(5)  
show_Second()  # 20

以上就是在使用Python的默認參數時要注意的事情!

留言