Fixing the Error: __init__() takes 1 positional argument but 2 were given

Python, as a versatile and widely-used programming language, often surprises developers with errors that seem simple yet can be puzzling. One such error is:

__init__() takes 1 positional argument but 2 were given

If you’ve encountered this, you’re not alone. This blog explains why this error occurs, how to fix it, and offers a deeper understanding of Python’s __init__() method.


Understanding the __init__() Method in Python

The __init__() method in Python is a special function (also called a constructor) that initializes an object’s state when it is created. This method is part of a class and allows you to set up initial attributes or perform setup tasks.

Here’s a basic example:

class Example:
    def __init__(self, value):
        self.value = value

In this case:

  • The first argument (self) refers to the instance being created.
  • Additional arguments (like value) are user-defined parameters you pass during object instantiation.

When the number of arguments passed to __init__() doesn’t match its definition, Python raises the error mentioned above.


Why Does This Error Occur?

The error typically arises when:

  1. You forgot to include self in the __init__() method definition.
  2. There’s a mismatch between the arguments in the __init__() method and what you provide during instantiation.

Here’s an example of code that triggers this error:

class Example:
    def __init__():
        print("This will cause an error")

# Creating an instance
obj = Example()

Output:

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

Breaking Down the Error

  • Python automatically passes the instance (self) as the first argument to __init__().
  • If self is missing in the method definition, Python interprets the instance as the first positional argument, resulting in a mismatch.

How to Fix __init__() takes 1 positional argument but 2 were given

1. Always Include self in __init__()

To avoid the error, ensure that the first parameter in __init__() is always self:

class Example:
    def __init__(self):
        print("This is correct!")

Now, creating an instance works as expected:

obj = Example()

Output:

This is correct!

2. Match Arguments in __init__() with Instantiation

If you add parameters to __init__(), ensure you provide matching arguments during object creation:

Incorrect:

class Example:
    def __init__(self, value):
        self.value = value

obj = Example()

Output:

TypeError: __init__() missing 1 required positional argument: 'value'

Correct:

class Example:
    def __init__(self, value):
        self.value = value

obj = Example(10)
print(obj.value)

Output:

10

Common Scenarios Where This Error Occurs

  • Inheritance without Proper __init__() Definitions When inheriting a class, ensure the parent’s __init__() method is called correctly.

Example:

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

class Child(Parent):
    def __init__(self, name):
        Parent.__init__(self, name)
  • Overriding Built-in Methods Overriding methods like __str__() or __repr__() improperly can lead to similar issues.

Debugging Tips

  • Check the Stack Trace: Look at the line where the error occurs and verify the arguments.
  • Verify the Class Definition: Ensure __init__() includes self and matches the required arguments.
  • Use Default Values: Provide default values to avoid missing arguments: class Example: def __init__(self, value=0): self.value = value

The Another way to solve this issue for DJango REST Framework is as below,

As we seen in our previous post “Developing REST API using functions in DRF application views” , we should how you can write the views using functions. Now, when we tried to change the same code for views from that post to write the views based on class, we got the following error,

TypeError at /user/1/

__init__() takes 1 positional argument but 2 were given

Solution :

For writing views based on functions, we had written the “urlpattern” in helloproject/helloapp/urls.py as,

urlpatterns = [
    path('user/<int:pk>/', views.user_by_pk),
]

So, when we tried to change the existing views based on function to views based on class, we completed modifying views.py but forgot to modify urls.py and run the server, and at the same time we got the error.

Hence as solution, we needed to change urlpatten from helloproject/helloapp/urls.py to add “.as_view()” to specifically mention we are using class based views.

urlpatterns = [
    path('user/<int:pk>/', views.user_by_pk.as_view()),
]

The error __init__() takes 1 positional argument but 2 were given is straightforward to resolve once you understand Python’s constructor mechanics. Always include self as the first argument in __init__() and ensure the arguments during object creation match its definition. By following these principles, you can avoid this common pitfall and write cleaner, error-free Python code.

Leave a Comment