close

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

Hello Guys, How are you all? Hope You all Are Fine. Today I face TypeError: method() takes 1 positional argument but 2 were given error in Python. So Here I am Explain to you all the possible solutions here.

Without Wasting your time, Lets start This Article to Solve This Error.

How TypeError: method() takes 1 positional argument but 2 were given Error Occurs ?

I have Class

class MyClassOne:

    def method(arg):
        print(arg)

I create Object and then I used that class

new_object = MyClassOne()

new_object.method("String")

But above code give me TypeError

TypeError: method() takes exactly 1 positional argument (2 given)

How To Solve TypeError: method() takes 1 positional argument but 2 were given ?

Question: How To Solve TypeError: method() takes 1 positional argument but 2 were given ?
Answer: The problem occurs because most methods do some work with the object they’re called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition.

Solution 1

Problem is occurs because most methods do some work with the object they’re called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

class MyClassOne:

    def method(self, arg):
        print(self)
        print(arg)

Now If you call method("String") on an instance of MyClassOne, it works as expected:

new_object = MyClassOne()
new_object .method("String")

Result is

String

Solution 2

You can also decorate the method with the builtin staticmethod() function to say so:

class MyClassOne:

    @staticmethod
    def method(arg):
        print(arg)
>>> new_object = MyClassOne()
>>> new_object.method("String")
String

Solution 3

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClassOne:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> new_object = MyClassOne()
>>> new_object.method("String")
String

This should solve your problem 🙂

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment