当使用关键字arguments和args, kwargs组合调用函数时,也会引发此异常
例子:
def function(a, b, c, *args, **kwargs):
print(f"a: {a}, b: {b}, c: {c}, args: {args}, kwargs: {kwargs}")
function(a=1, b=2, c=3, *(4,))
它会提高:
TypeError Traceback (most recent call last)
<ipython-input-4-1dcb84605fe5> in <module>
----> 1 function(a=1, b=2, c=3, *(4,))
TypeError: function() got multiple values for argument 'a'
而且当你在继承中滥用它时,它会变得更复杂。所以要小心我们这些东西!
1-使用关键字arguments和args调用函数:
class A:
def __init__(self, a, b, *args, **kwargs):
self.a = a
self.b = b
class B(A):
def __init__(self, *args, **kwargs):
a = 1
b = 2
super(B, self).__init__(a=a, b=b, *args, **kwargs)
B(3, c=2)
例外:
TypeError Traceback (most recent call last)
<ipython-input-5-17e0c66a5a95> in <module>
11 super(B, self).__init__(a=a, b=b, *args, **kwargs)
12
---> 13 B(3, c=2)
<ipython-input-5-17e0c66a5a95> in __init__(self, *args, **kwargs)
9 a = 1
10 b = 2
---> 11 super(B, self).__init__(a=a, b=b, *args, **kwargs)
12
13 B(3, c=2)
TypeError: __init__() got multiple values for argument 'a'
2-调用一个包含关键字参数的函数和kwargs:
class A:
def __init__(self, a, b, *args, **kwargs):
self.a = a
self.b = b
class B(A):
def __init__(self, *args, **kwargs):
a = 1
b = 2
super(B, self).__init__(a=a, b=b, *args, **kwargs)
B(**{'a': 2})
例外:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-c465f5581810> in <module>
11 super(B, self).__init__(a=a, b=b, *args, **kwargs)
12
---> 13 B(**{'a': 2})
<ipython-input-7-c465f5581810> in __init__(self, *args, **kwargs)
9 a = 1
10 b = 2
---> 11 super(B, self).__init__(a=a, b=b, *args, **kwargs)
12
13 B(**{'a': 2})
TypeError: __init__() got multiple values for keyword argument 'a'