python函数参数中添加默认值

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 “<stdin>”, 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 “<stdin>”, line 1, in <module>
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

“””

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理