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

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

The error says that as per the definition of method, it accepts no arguments, but we provided an an argument.

Recreate Python TypeError

An example class definition that could recreate this error is given below.

Python Program

class Laptop:
	def details():
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()
Run this program

Output

Traceback (most recent call last):
  File "example1.py", line 6, in <module>
    laptop1.details()
TypeError: details() takes 0 positional arguments but 1 was given

You might be wondering that you have not passed any arguments when you called details() method on the laptop1 object. But, why Python is throwing the TypeError?

Here is why. By default, if the method is not a static python method, then implicitly the object (self) is passed as argument. So, when you called laptop1.details(), it is actually being called as laptop1.details(laptop1).

Solution for TypeError

And to comply this inbuilt behavior, we need to provide an argument in the definition of details() method as shown below:

Python Program

class Laptop:
	def details(self):
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()
Run this program

Output

Hello! I am a laptop.

Also, there is another way, if the method is meant to be a static method. You can tell Python Interpreter that this method is a static method using @staticmethod as shown below.

Python Program

class Laptop:
	@staticmethod
	def details():
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()
Run this program

Output

Hello! I am a laptop.

Summary

In this tutorial of Python Examples, we have learned to solve the TypeError: method() takes 0 positional arguments but 1 was given, with the help of example programs.