## DEV Community is a community of 894,881 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

codemee

Posted on

# 你的參數預設值不是你想的預設值

## 參數預設值只會在定義函式時產生 1 次

``````>>> def print_time(t):
...     t_struct = time.localtime(t)
...     print(F'{t_struct[3]:02d}:{t_struct[4]:02d}:{t_struct[5]:02d}')
>>>
``````

``````>>> print_time(time.time())
22:09:19
>>> print_time(time.time())
22:09:22
>>> print_time(time.time())
22:09:24
>>>
``````

``````>>> def print_time(t = time.time()):
...     t_struct = time.localtime(t)
...     print(F'{t_struct[3]:02d}:{t_struct[4]:02d}:{t_struct[5]:02d}')
>>>
``````

``````>>> print_time(time.time())
22:05:44
>>> print_time()
22:05:33
>>> print_time()
22:05:33
>>> print_time()
22:05:33
>>>
``````

## 檢查是否有傳入參數再計算預設值

``````>>> def print_time(t = None):
...     if t == None:
...         t = time.time()
...     t_struct = time.localtime(t)
...     print(F'{t_struct[3]:02d}:{t_struct[4]:02d}:{t_struct[5]:02d}')
>>>
``````

``````>>> print_time()
22:16:52
>>> print_time()
22:16:54
>>> print_time(time.time())
22:17:03
>>>
``````

## 小心使用可變的資料當預設值

``````>>> def add_list(l = []):
...     print(l)
...     sum = 0;
...     for i in l:
...         sum += i
...     print(sum)
...     l.append(1)
>>>
``````

``````>>> add_list([1, 2, 3])
[1, 2, 3]
6
>>>
``````

``````>>> add_list()
[]
0
[1]
1
[1, 1]
2
[1, 1, 1]
3
>>>
``````

## 小結

Python 雖然有許多便利的語法, 但是如果沒有注意相關的細節, 往往會在遇到異常結果時不知所措, 但只要瞭解實際的運作方式, 就可以用正確的方式撰寫程式。