为什么关键字参数(默认情况下)采用位置参数的值?

时间:2020-02-21 14:46:43

标签: python function parameters arguments

请帮我了解下一种情况。 为什么默认情况下参数使用位置参数的值?

代码:

def func(a, b, c = "value by default", d = "one more value by default", *args, e, **kwargs):
    print("'a' is: ", a)
    print("'b' is: ", b)
    print("'c' is: ", c)
    print("'d' is: ", d)
    print("'args' is: ", args)
    print("'e' is: ", e)
    print("'kwargs' is: ", kwargs)
    return a, b, c, d, args, e, kwargs

func('A', 'B', 3, 4, 5, e = 12, f = 20, g = 30)

输出

# 'a' is:  A
# 'b' is:  B
# 'c' is:  3
# 'd' is:  4
# 'args' is:  (5,)
# 'e' is:  12
# 'kwargs' is:  {'f': 20, 'g': 30}

我正在等待其他结果,例如:

# 'a' is:  A
# 'b' is:  B
# 'c' is:  "value by default"
# 'd' is:  "one more value by default"
# 'args' is:  (3, 4, 5)
# 'e' is:  12
# 'kwargs' is:  {'f': 20, 'g': 30}

如果我尝试以这种方式调用函数:

# func('A', 'B', 3, 4, 5, c = "C", d = "D",e = 12, f = 20, g = 30) 

我遇到这样的错误# TypeError: func() got multiple values for argument 'c' 看起来我可能默认情况下使用关键字参数而没有附加参数* args。 像这样:

func('A', 'B', c = "C", d = "D", e = 12, f = 20, g = 30)

输出:

# 'a' is:  A
# 'b' is:  B
# 'c' is:  C
# 'd' is:  D
# 'args' is:  ()
# 'e' is:  12
# 'kwargs' is:  {'f': 20, 'g': 30}

0 个答案:

没有答案