The error message TypeError: __init__() takes 1 positional argument but 2 were given usually occurs when we try to instantiate a class and pass one additional argument while the __init__() method (the constructor) of that class is defined to take only one argument.
Now let’s analyze the error message:
The constructor method in a Python class, __init__(), is responsible for initializing the class instance.
The constructor is defined to take a single argument, as shown by the notation 1 positional argument.
2 were given indicates that we are attempting to use two arguments to create an instance of the class.
Here’s a quick example to help us understand this problem:
class SampleClass:def __init__(self):passclassObj = SampleClass(1) # This will raise the TypeError
According to the error message, the __init__() method receives two arguments, but we only pass the number 1 as an argument. This is because the interpreter reads the statement classObj = SampleClass(1) as SampleClass.__init__(classObj, 1). So, a total of two arguments are being passed in this case.
When we create an instance of SampleClass, Python automatically passes the instance itself as the first argument. Most methods do some work with the object they are called on. To reference the object within the method, a common convention is to use the parameter named self as the first argument inside the function definition.
We must ensure that the number of arguments we provide when creating a class instance equals the number of parameters specified in the __init__() method in order to resolve this error.
SampleClass with no extra argumentsTo resolve the error, we can instantiate SampleClass without passing any additional argument:
class SampleClass:def __init__(self):print("In __init__ method.")classObj = SampleClass()
__init__() method to accept two argumentsWe can also fix the issue by modifying __init__() method to accept two arguments, as shown in the example below:
class SampleClass:def __init__(self, arg1):self.arg1 = arg1classObj = SampleClass(1)
@staticmethod decoratorApart from this, we can use the @staticmethod decorator to prevent from passing the instance itself as the first argument:
class SampleClass:@staticmethoddef __init__(self):print(self)classObj = SampleClass(1)
Free Resources