存在可变长度参数时使用默认参数

时间:2019-05-21 08:59:49

标签: python python-3.x python-2.7

如果我不提供任何值,我想将参数C默认设置为20。

这怎么可能?

functypes(1,2,,4,5,6,id='jijo',job='engineer')

我已经尝试过了,但是显示语法错误:

functypes(1,2,,4,5,6,)
                  ^
SyntaxError: invalid syntax

def functypes(a,b,c=20,*y,**Z):
    print("the values of a,b,c are",a,b,c)
    for y1 in y:
        print("The values in Y are",y1,",",end='')
    for z1,z2 in Z.items():
        print("The values in Z are",z1,z2)

以下调用工作正常:

functypes(1,2,,4,5,6,id='jijo',job='engineer')

4 个答案:

答案 0 :(得分:2)

def functypes(a,b,c=20,*y,**Z):更改为def functypes(a,b,*y,c=20,**Z):,这将保留c并保持所需的值,因为c是键值对,需要添加vefore键值

def functypes(a,b,*y,c=20,**Z):
    print("the values of a,b,c are",a,b,c)
    for y1 in y:
        print("The values in Y are",y1,",",end='\n')
    for z1,z2 in Z.items():
        print("The values in Z are",z1,z2)

functypes(1,2,3,4,5,6,id='jijo',job='engineer')

""" output 
the values of a,b,c are 1 2 20
The values in Y are 3 ,
The values in Y are 4 ,
The values in Y are 5 ,
The values in Y are 6 ,
The values in Z are id jijo
The values in Z are job engineer
"""

答案 1 :(得分:2)

将默认arg放在* args之后,使其成为keyword-only参数,只能按名称指定,而不能按位置指定。

def functypes(a,b,*y,c=20,**Z):
    print("the values of a,b,c are",a,b,c)
    for y1 in y:
        print("The values in Y are",y1,",",end='')
    for z1,z2 in Z.items():
        print("The values in Z are",z1,z2)

functypes(1,4,5,6,7,8,c=9,id='jijo',job='engineer') #take c as 9
functypes(1,4,5,6,7,8,id='jijo',job='engineer') #take c as 20

答案 2 :(得分:1)

您不能。 Python不允许传递显式的空参数。换句话说,不允许在函数调用中编写连续的逗号(,,),因此只能在空参数之后传递关键字参数。

一个常见的习惯用法是使用None值:

def functypes(a,b,c=None,*y,**Z):
    if c is None: c=20
    print("the values of a,b,c are",a,b,c)
    for y1 in y:
        print("The values in Y are",y1,",",end='')
    for z1,z2 in Z.items():
        print("The values in Z are",z1,z2)

然后您可以使用:functypes(1,2,None,4,5,6,id='jijo',job='engineer')


或者,您可以显式地将y参数作为关键字传递:functypes(1,2,y=[4,5,6],id='jijo',job='engineer'),但实际上看起来像是反模式...

答案 3 :(得分:0)

有人发布了,这行得通。

functypes(1,2,*[3,4,5,6],id='jijo',job='engineer')