python函数参数中添加默认值

python语言和C++一样,支持函数定义的时候带有默认值。但是,携带默认值的参数,都需要放在函数参数的后面,否则调用的时候会报错,提示没有默认值的参数没有赋值。

python语言,利用星号(*)可以设计一个默认值位于中间位置的默认值,主要是利用python支持通过制定参数名称的特性。

例如: file """

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

"""

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章