TypeError: method()接受1个位置参数,但给出2个

时间:2022-10-16 23:20:38

If I have a class ...

如果我有课……

class MyClass:

    def method(arg):
        print(arg)

... which I use to create an object ...

…我用它来创建一个对象……

my_object = MyClass()

... on which I call method("foo") like so ...

…我称之为方法(“foo”),就像这样…

>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

... why does Python tell me I gave it two arguments, when I only gave one?

…为什么Python告诉我我给出了两个参数,而我只给出了一个?

6 个解决方案

#1


157  

In Python, this:

在Python中,这个:

my_object.method("foo")

... is syntactic sugar, which the interpreter translates behind the scenes into:

…为句法糖,译员将其翻译为:

MyClass.method(my_object, "foo")

... which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.

…正如你所看到的,它确实有两个参数——只是第一个是隐含的,从调用者的角度来看。

This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

这是因为大多数方法对它们所调用的对象做了一些工作,所以需要有某种方式使该对象在方法中被引用。按照惯例,第一个参数在方法定义中称为self:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

If you call method("foo") on an instance of MyNewClass, it works as expected:

如果您在MyNewClass的实例上调用method(“foo”),它会像预期的那样工作:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod() function to say so:

偶尔(但不是经常),您实际上并不关心方法绑定到的对象,在这种情况下,您可以使用builtin staticmethod()函数来修饰方法:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

... in which case you don't need to add a self argument to the method definition, and it still works:

…在这种情况下,您不需要在方法定义中添加一个self参数,它仍然可以工作:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

#2


8  

Something else to consider when this type of error is encountered:

当遇到这种类型的错误时,需要考虑一些其他因素:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an init() where there was object inheritance.

我遇到了这个错误信息,发现这个帖子很有用。在我的例子中,我重写了一个init(),其中包含对象继承。

The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:

继承的示例相当长,因此我将跳到一个不使用继承的更简单的示例:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

结果是:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).

PyCharm没注意到这个错字。记事本++ +(其他编辑器/IDE的功能)也是如此。

Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.

当然,这是一个“不接受参数”的类型错误,就Python中的对象初始化而言,它与“得到两个”没什么不同。

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.

处理主题:如果语法正确,将使用重载初始化器,但如果不正确,将忽略该初始化器,而使用内置的初始化器。对象不会期望/处理这个,错误被抛出。

In the case of the sytax error: The fix is simple, just edit the custom init statement:

在sytax错误的情况下:修复很简单,只需编辑自定义init语句:

def __init__(self, name):
    self.name = name

#3


2  

It occurs when you don't specify the no of parameters the init() or any other method looking for

当您没有指定init()或任何其他方法寻找的参数的no时,就会发生这种情况

For example

例如

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme ,it gives you an error like that TypeError: __init__() takes 1 positional argument but 6 were given

当您运行上面的程序时,它会给您一个类似类型错误的错误:__init__()接受一个位置参数,但是给出了6个

how we can get rid of this thing?

我们怎样才能摆脱这个东西?

just pass the parameters ,what init() method looking for

只需传递参数,即init()方法要查找的内容

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

#4


-1  

To me it usually happens when I have two methods with same methods defined twice (by mistake), like below:

对我来说,这通常发生在我有两个方法同时定义了两次相同的方法时(错误地),如下所示:

class A(object):   
  def a(one):
    pass   
  def a(one, two):
    pass

#5


-1  

Pass cls parameter into @classmethod to resolve this problem.

将cls参数传递到@classmethod以解决这个问题。

@classmethod
def test(cls):
    return ''

#6


-3  

Also, as in my case, make sure you actually still have a parameter in the function. I overlooked that.

同样,在我的例子中,确保函数中仍然有一个参数。我忽略了这一点。

I had

我有

class MyClass():
    def foo(foo_string):
        return get_bar(foo_string)

When I went and changed the method and removed the parameter, I forgot to update my other files that used the same function.

当我修改方法并删除参数时,我忘记更新使用相同函数的其他文件。

TLDR; Refactor your code.

TLDR;重构您的代码。

#1


157  

In Python, this:

在Python中,这个:

my_object.method("foo")

... is syntactic sugar, which the interpreter translates behind the scenes into:

…为句法糖,译员将其翻译为:

MyClass.method(my_object, "foo")

... which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.

…正如你所看到的,它确实有两个参数——只是第一个是隐含的,从调用者的角度来看。

This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

这是因为大多数方法对它们所调用的对象做了一些工作,所以需要有某种方式使该对象在方法中被引用。按照惯例,第一个参数在方法定义中称为self:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

If you call method("foo") on an instance of MyNewClass, it works as expected:

如果您在MyNewClass的实例上调用method(“foo”),它会像预期的那样工作:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod() function to say so:

偶尔(但不是经常),您实际上并不关心方法绑定到的对象,在这种情况下,您可以使用builtin staticmethod()函数来修饰方法:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

... in which case you don't need to add a self argument to the method definition, and it still works:

…在这种情况下,您不需要在方法定义中添加一个self参数,它仍然可以工作:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

#2


8  

Something else to consider when this type of error is encountered:

当遇到这种类型的错误时,需要考虑一些其他因素:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an init() where there was object inheritance.

我遇到了这个错误信息,发现这个帖子很有用。在我的例子中,我重写了一个init(),其中包含对象继承。

The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:

继承的示例相当长,因此我将跳到一个不使用继承的更简单的示例:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

结果是:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).

PyCharm没注意到这个错字。记事本++ +(其他编辑器/IDE的功能)也是如此。

Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.

当然,这是一个“不接受参数”的类型错误,就Python中的对象初始化而言,它与“得到两个”没什么不同。

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.

处理主题:如果语法正确,将使用重载初始化器,但如果不正确,将忽略该初始化器,而使用内置的初始化器。对象不会期望/处理这个,错误被抛出。

In the case of the sytax error: The fix is simple, just edit the custom init statement:

在sytax错误的情况下:修复很简单,只需编辑自定义init语句:

def __init__(self, name):
    self.name = name

#3


2  

It occurs when you don't specify the no of parameters the init() or any other method looking for

当您没有指定init()或任何其他方法寻找的参数的no时,就会发生这种情况

For example

例如

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme ,it gives you an error like that TypeError: __init__() takes 1 positional argument but 6 were given

当您运行上面的程序时,它会给您一个类似类型错误的错误:__init__()接受一个位置参数,但是给出了6个

how we can get rid of this thing?

我们怎样才能摆脱这个东西?

just pass the parameters ,what init() method looking for

只需传递参数,即init()方法要查找的内容

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

#4


-1  

To me it usually happens when I have two methods with same methods defined twice (by mistake), like below:

对我来说,这通常发生在我有两个方法同时定义了两次相同的方法时(错误地),如下所示:

class A(object):   
  def a(one):
    pass   
  def a(one, two):
    pass

#5


-1  

Pass cls parameter into @classmethod to resolve this problem.

将cls参数传递到@classmethod以解决这个问题。

@classmethod
def test(cls):
    return ''

#6


-3  

Also, as in my case, make sure you actually still have a parameter in the function. I overlooked that.

同样,在我的例子中,确保函数中仍然有一个参数。我忽略了这一点。

I had

我有

class MyClass():
    def foo(foo_string):
        return get_bar(foo_string)

When I went and changed the method and removed the parameter, I forgot to update my other files that used the same function.

当我修改方法并删除参数时,我忘记更新使用相同函数的其他文件。

TLDR; Refactor your code.

TLDR;重构您的代码。