python語言和C++一樣,支持函數定義的時候帶有默認值。但是,攜帶默認值的參數,都需要放在函數參數的後面,否則調用的時候會報錯,提示沒有默認值的參數沒有賦值。
python語言,利用星號(*)可以設計一個默認值位於中間位置的默認值,主要是利用python支持通過制定參數名稱的特性。
例如: """
def fun(a,b,c): ... print(a, b, c) ... fun(1,2,3) 1 2 3 def fun_with_default_value(a, b=2, c = 3): ... print(a, b, c) ... fun_with_default_value(1) 1 2 3 fun_with_default_value(1, 4) 1 4 3
def fun_with_default_value(a, b=2, c): ... print(a, b, c) ... File "
", line 1 SyntaxError: non-default argument follows default argument def fun_with_default_value(a, b=2, *, c): ... print(a, b, c) ...
fun_with_default_value(1, 5) Traceback (most recent call last): File "
", line 1, in TypeError: fun_with_default_value() missing 1 required keyword-only argument: 'c' fun_with_default_value(1, c=5) 1 2 5 fun_with_default_value(1, 3, c=5) 1 3 5
"""