문제

Look at this example (using python 2.7.6):

>>> def func(a, b, c, d):  
    print a, b, c, d

>>> func(1, c = 3, *(2,), **{'d':4})
1 2 3 4

Up to here, this is fine. But, why the following call fails?

>>> func(1, b = 3, *(2,), **{'d':4})

Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    func(1, b = 3, *(2,), **{'d':4})
TypeError: func() got multiple values for keyword argument 'b'
도움이 되었습니까?

해결책

It can be better understood with another function signature

>>> def func(*args, **kw):
        print(args, kw)


>>> func(1, b = 3, *(2,), **{'d':4})
(1, 2) {'b': 3, 'd': 4}

So, the positional arguments are put together and so are the keyword arguments.

Using the original signature, it means both 2 and 3 will be assigned to b, which is not valid.

PS: Because a simple tuple unpacking does not provide names, the values will be treated as positional arguments.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top