TypeError: 在 Python 中得到多个参数值
TypeError: got multiple values for argument in Python
当我们在函数调用中用关键字参数覆盖位置参数的值时,会出现 Python“TypeError: got multiple values for argument”。
要解决该错误,请确保只为参数传递一个值一次,并指定self
为类方法中的第一个参数。
下面是错误如何发生的示例。
def get_employee(name, **kwargs): return {'name': name, **kwargs} # ⛔️ TypeError: get_employee() got multiple values for argument 'name' result = get_employee('Alice', name='Alice') print(result)
该get_employee
函数采用name
位置参数和关键字参数。
name
位置参数传递了一个值,并使用关键字参数为其设置了一个值。 name
不允许为同一参数指定多个值。
从函数调用中移除关键字参数
name
解决错误的一种方法是从函数调用中删除关键字参数。
def get_employee(name, **kwargs): return {'name': name, **kwargs} result = get_employee('Alice') print(result) # 👉️ {'name': 'Alice'}
我们只调用了带有参数位置参数的函数name
。
仅将值作为关键字参数传递
或者,您可以name
仅将参数作为关键字参数传递。
def get_employee(name, **kwargs): return {'name': name, **kwargs} result = get_employee(name='Alice', salary=100) print(result) # 👉️ {'name': 'Alice', 'salary': 100}
我们get_employee
使用 2 个关键字参数调用该函数,因此 Python 不再对提供参数的值感到困惑。
忘记指定self
为类中的第一个参数
Another common cause of the error is forgetting to specify self
as the first
argument in a class method.
class Employee(): # 👇️ forgot to specify `self` as first arg def get_name(name=None): return name emp1 = Employee() # ⛔️ TypeError: Employee.get_name() got multiple values for argument 'name' emp1.get_name(name='Alice')
We didn’t specify self as the first
argument in the get_name
method which caused the error.
self
as the first argument to the method.self
represents an instance of the class, so when we assign a variable as
self.my_var = 'some value'
, we are declaring an instance variable – a variable
unique to each instance.
You could name this argument anything because the name self
has no special
meaning in Python.
# Specify self
as the first argument in the method
To solve the error, make sure to specify self
as the first argument in the
method.
class Employee(): # ✅ specified self as first arg def get_name(self, name=None): return name emp1 = Employee() print(emp1.get_name(name='Alice')) # 👉️ "Alice"
Now that we set self
as the first argument in the method, everything works as
expected.
The issue was caused because Python automatically passes the instance (self
)
as the first argument to the method.
So, if you don’t explicitly specify the self
arg in the definition of the
method, Python passes self
and we pass name='Alice'
as a value for the same
argument.
class Employee(): # 👇️ forgot to specify `self` as first arg def get_name(name=None): return name emp1 = Employee() # ⛔️ TypeError: Employee.get_name() got multiple values for argument 'name' print(emp1.get_name(name='Alice'))
emp1.get_name()
, it will get passed the instance as the first argument, so you should make sure to explicitly specify it when declaring the method.Otherwise, you and Python might end up passing a value for the same argument,
which is very confusing.
请注意,您应该只指定self
实例方法(您在类实例上调用的方法)中的第一个参数。
如果你有一个基本函数,你不应该指定一个self
参数。