在具有可变参数的函数中使用默认参数。这可能吗?

Kar*_*hat 5 python

我有以下代码。在此,我想利用为'a'提供的可选参数;即“ 5”,而不是“ 1”。如何使元组“数字”包含的第一个元素为1而不是2?

def fun_varargs(a=5, *numbers, **dict):
    print("Value of a is",a)
    for i in numbers:
        print("Value of i is",i)
    for i, j in dict.items():
        print("The value of i and j are:",i,j)

fun_varargs(1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)
Run Code Online (Sandbox Code Playgroud)

Vic*_*bot 3

属性.__defaults__在元组中提供默认参数。你可以在这里使用它。

>>> def fun_varargs(a = 5, *numbers, **dict):
...     print("value of a is", a)
...     for i in numbers:
...             print("value of i is", i)
...     for i, j in dict.items():
...             print("The value of i and j are:", i,j)
... 

>>> fun_varargs(fun_varargs.__defaults__[0],1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)
value of a is 5
value of i is 1
value of i is 2
value of i is 3
value of i is 4
value of i is 5
value of i is 6
value of i is 7
value of i is 8
value of i is 9
value of i is 10
The value of i and j are: Jack 111
The value of i and j are: John 222
The value of i and j are: Tom 333
Run Code Online (Sandbox Code Playgroud)