TypeError: __init__() takes 0 positional arguments but 1 was given

This post is about one of the type errors that occur when dealing with the self parameter in Python classes.

Table of Contents

For more information about argument types and parameter types, see Argument Types in Python Functions, Parameter Types in Python Functions.


Explanation of the Error

This type of error can occur in class methods. The error message points to the line where the class method is called.

...
    class_instance = MyClass()
TypeError : MyClass.__init__() takes 0 positional arguments but 1 was given
...
    class_instance.method()
TypeError : MyClass.method() takes 0 positional arguments but 1 was given

What does the error message mean?

This error message indicates that no parameters were specified for a class method. It takes 0 arguments, respectively.

The main reason for the error is the absence of the required self parameter in the class method.

def __init__(): # <-- self is missing
    pass
def method(): # <-- self is missing
    pass

Case Where __init__ or Another Method Has Some Parameters

In the following example, the method has some parameters. The first parameter of the method always corresponds to an instance of the class, even if it is not named with the word "self".

In this case, the method can accept two positional arguments: an instance of the class (for param1) and a value for param2.

def method(param1, param2): # forgot to add "self"
    pass
class_instance.method("value1", "value2")

Using this method, we think we're passing values for our parameters: value1 to param1 and value2 to param2. In fact, three arguments are passed to the method. An instance of the class, "value1", and "value2".

We get an error with a different number of arguments.

...
    class_instance.method("value1", "value2")
TypeError: MyClass.method() takes 2 positional arguments but 3 were given

The solution is the same: you need to add the self parameter.

def method(self, param1, param2):
    pass

Popular posts from this blog

Tkinter Button Widget