about 3 years ago

Provide Optional Behavior with Keyword Arguments

Keyword arguments 好處有:

  1. 呼叫時和參數名稱綁在一起,讓程式碼更清楚
  2. 讓函式有預設值,使用上更方便
  3. 讓函式有機會達到向後相容

假設本來的函式如下

def flow_rate(weight_diff, time_diff, period=1):
    return (weight_diff / time_diff) * period

如果後來程式修改了

def flow_rate(weight_diff, time_diff,
              period=1, units_per_kg=1):
    return ((weight_diff / units_per_kg) / time_diff) * period

但是使用舊函式的程式不需要修改

flow_per_second = flow_rate(weight_diff, time_diff)
flow_per_hour = flow_rate(weight_diff, time_diff, period=3600)
← Effective Python 心得筆記: Item 18 Effective Python 心得筆記: Item 20 →
 
comments powered by Disqus