TypeError: method() takes 1 positional argument but 2 were given

前端 未结 9 1130
孤街浪徒
孤街浪徒 2020-11-22 05:02

If I have a class...

class MyClass:

    def method(arg):
        print(arg)

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

my_objec         


        
9条回答
  •  耶瑟儿~
    2020-11-22 05:45

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

提交回复
热议问题