如何设置星形参数的默认值?

时间:2016-06-02 09:09:12

标签: python python-3.x

我有一个接受*args的函数,但我想设置一个默认元组,以防没有提供。 (这不可能通过def f(*args=(1, 3, 5))提出SyntaxError。)最好的方法是什么?预期的功能如下所示。

f()
# I received 1, 2, 3!

f(1)
# I received 1!

f(9, 3, 72)
# I received 9, 3, 72!

以下函数g将提供正确的功能,但我更喜欢*args

def g(args=(1, 2, 3)):
    return "I received {}!".format(', '.join(str(arg) for arg in args))

g()
# I received 1, 2, 3!

g((1,))
# I received 1!

g((9, 3, 72))
# I received 9, 3, 72!

3 个答案:

答案 0 :(得分:11)

你可以检查你的函数中args是否真实:

def g(*args):
    if not args:
        args = (1, 2, 3)
    return "I received {}!".format(', '.join(str(arg) for arg in args))

如果没有args传递给函数,它将导致一个空元组,其值为False

答案 1 :(得分:6)

如果没有收到任何参数,args将是一个空元组。您无法在方法签名本身中添加默认值,但可以检查args是否为空,并将其替换为函数内的回退值。

def g(*args):
    if not args: 
        args = (1, 2, 3)
    return 'I received {}!'.format(', '.join(str(arg) for arg in args))

答案 2 :(得分:4)

def g(*args):
    if not args:
        args = [1, 3, 5]
    return "I received {}!".format(', '.join(str(arg) for arg in args))