Typeerror: Takes 1 Positional Argument But 2 Were Given – How To Solve It?

typeerror: takes 1 positional argument but 2 were given

“Typeerror: takes 1 positional argument but 2 were given” is a common error related to a method of an object of a class. The below explanations can help you know more about the cause of this error and solutions.

How does this error happen?

Basically, this error happens due to the many following reasons:

Firstly, it might be because you forgot to declare the “self” argument when defining a method of a class.

Below is an example for this reason:

class Example:
	def example(s):
		return "Example: you forgot the `self` argument"

print(Example().example("abcdef"))

Secondly, you might have forgotten to declare the second argument in the definition of the method of a class.

Here is an example:

class Example:
	def example(self):
		return "Example: you forgot the second argument s"

s = "example str"
print(Example().example(s))

Thirdly, as clearly as the error indicates, you are passing two arguments to the method which takes only one.

For example:

class Example:
	def example(self):
		return "Example: this method only takes 1 post argument"

str1 = "example str"
print(Example().example(str1))

How to solve the error “Typeerror: takes 1 positional argument but 2 were given”

Solution 1: Declare the ‘self’ argument in the method definition

Any method of a class in Python must be declared with a “self” argument in its prototype. Missing the “self” argument is a common error with most Python beginners. Look at the following example to understand more:

class Example:
	def example(self, s):
		return s

print(Example().example("abcdef"))

Output:

abcdef

Solution 2: Declare the second argument in the method

Another way to fix this error is to declare the second argument in the method prototype if that was your mistake. Let’s go into detail with the following sample code:

class Example:
	def example(self, s):
		return s

s = "example str"
print (Example().example(s))

Output:

example str

Solution 3: Check the number of arguments passed carefully

We recommend you check the prototype method and make sure you didn’t pass more than the number of arguments you had declared in the method:

class Example:
	def example(self):
		return "Example: this method only takes 1 post argument"

print (Example().example())

Output:

Example: this method only takes 1 post argument

Summary

We have learned how to deal with the error “Typeerror: takes 1 positional argument but 2 were given” in Python. By checking the prototype carefully and finding out the reasons causing this problem in this tutorial, you can quickly solve it.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *