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

如果我有课…

class MyClass:

    def method(arg):
        print(arg)

…我用来创建对象的…

my_object = MyClass()

我这样称呼method("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)

…为什么当我只给出一个参数时,Python告诉我给它两个参数?

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…

>>> 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?


回答 0

在Python中,这是:

my_object.method("foo")

…是语法糖,口译员在后台将其翻译为:

MyClass.method(my_object, "foo")

您可以看到,它确实有两个参数-从调用者的角度来看,只是第一个参数是隐式的。

这是因为大多数方法会对被调用的对象进行某些处理,因此需要某种方法在该方法内部引用该对象。按照惯例,第一个参数self在方法定义内调用:

class MyNewClass:

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

如果您呼叫method("foo")的实例MyNewClass,它会按预期运作:

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

有时(但不经常),您实际上不在乎您的方法所绑定的对象,在这种情况下,您可以使用内置函数来修饰该方法,staticmethod()例如:

class MyOtherClass:

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

…在这种情况下,您无需self在方法定义中添加参数,它仍然有效:

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

In Python, this:

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:

class MyNewClass:

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

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

>>> 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:

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:

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

回答 1

遇到此类错误时要考虑的其他事项:

我遇到了这个错误消息,发现这篇文章很有帮助。事实证明,我重写了__init__()存在对象继承的位置。

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

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")

结果是:

<__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没有抓住这种错别字。Notepad ++也没有(其他编辑器/ IDE也可能)。

当然,这是一个“不带任何参数”的TypeError,与期望得到一个的“得到两个”没有太大区别,就Python中的对象初始化而言。

解决主题:在语法上正确的情况下将使用重载初始化程序,但在语法上正确的情况下将被使用,而是使用内置初始化程序。该对象不会期望/处理此问题,并且会引发错误。

如果出现sytax错误:修复很简单,只需编辑自定义init语句即可:

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

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.

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).

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.

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:

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

回答 2

简单来说。

在Python中,您应该将self参数作为第一个参数添加到类中所有已定义的方法中:

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

然后,您可以根据自己的直觉使用您的方法:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

这应该可以解决您的问题:)

为了更好地理解,您还可以阅读以下问题的答案:自我的目的是什么?

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

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

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?


回答 3

Python的新手**,以错误的方式使用Python的功能时遇到了这个问题。尝试从某处调用此定义:

def create_properties_frame(self, parent, **kwargs):

使用没有双星的通话会导致问题:

self.create_properties_frame(frame, kw_gsp)

TypeError:create_properties_frame()接受2个位置参数,但给出了3个

解决方案是**在参数中添加:

self.create_properties_frame(frame, **kw_gsp)

Newcomer to Python, I had this issue when I was using the Python’s ** feature in a wrong way. Trying to call this definition from somewhere:

def create_properties_frame(self, parent, **kwargs):

using a call without a double star was causing the problem:

self.create_properties_frame(frame, kw_gsp)

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

回答 4

当您未指定参数No __init__()或任何其他寻找方法时,就会发生这种情况。

例如:

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")

当您运行上述程序时,它给您这样的错误:

TypeError:__init __()接受1个位置参数,但给出了6个

我们如何摆脱这件事?

只需传递参数,__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))

It occurs when you don’t specify the no of parameters the __init__() or any other method looking for.

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

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

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))

回答 5

您实际上应该创建一个类:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
    return self.acc

You should actually create a class:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
    return self.acc

回答 6

就我而言,我忘记添加 ()

我正在这样调用方法

obj = className.myMethod

但是应该是这样

obj = className.myMethod()

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

回答 7

cls参数传递到@classmethod以解决此问题。

@classmethod
def test(cls):
    return ''

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。