[Solved] TypeError: method() takes 1 positional argument but 2 were given

From teaching hundreds of thousands of students Python, I found this error to be a classic. I think understanding classes is hard enough, but many coders who’ve just started to learn about Python are rightly confused ? about the TypeError that complains about too few positional arguments. Let’s resolve this confusion once and for all, shall we?

Problem Formulation: Method Takes One Arguments But Two Are Given

Consider the following minimal example where this error occurs. Most occurrences of this error are variants of the following usage—you define method with one argument, but when calling it with one argument, Python raises the error:

class YourClass:
    def method(your_arg): # One positional argument defined
        print(your_arg)

o = YourClass()
o.method('finxter') # Calling it with one argument

However, this code snippet raises an error: TypeError: method() takes 1 positional argument but 2 were given

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 6, in <module>
    o.method('finxter')
TypeError: method() takes 1 positional argument but 2 were given

Here’s how it looks in my IDLE shell:

What is the origin of this error?

Solution: First Positional Argument Must be Self

You can solve the TypeError: method() takes 1 positional argument but 2 were given by adding an argument named self to your method definition as a first positional argument. But when calling it, you skip the name, so you’d define method(self, arg) but call method(arg). Python implicitly passes a reference to the instance as a first method argument, that’s why it tells you that two arguments are given.

class YourClass:
    def method(self, your_arg): # One positional argument defined
        print(your_arg)

o = YourClass()
o.method('finxter') # Calling it with one argument

Now, the output doesn’t contain an error:

finxter

The reason is simple: the first keyword is a reference to the instance on which it is called. So, if you call

o.method('finxter')

Python automatically converts it to

YourClass.method(o, 'finxter')

passing the instance on which it is called as a first positional argument usually named self. This is just syntactic sugar but you need to understand it once to overcome your confusion forever.

Background

The name self is, by convention, the name of the first argument of a Python class method. The variable self points to the concrete instance on which the method is called. It is used within the method to access attributes and other methods of the same instance. The caller of the method does not explicitly pass the instance into self but leaves it to the Python interpreter to pass it automatically. For example, given an object car, Python automatically converts the method call car.drive() to drive(self=car).

Feel free to join our community of ambitious coders and download your cheat sheets: