Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: function takes exactly 1 argument (2 given)

I have this method in a class

class CatList:

    lista = codecs.open('googlecat.txt', 'r', encoding='utf-8').read()
    soup = BeautifulSoup(lista)    
    # parse the list through BeautifulSoup
    def parseList(tag):
        if tag.name == 'ul':
            return [parseList(item)
                    for item in tag.findAll('li', recursive=False)]
        elif tag.name == 'li':
            if tag.ul is None:
                return tag.text
            else:
                return (tag.contents[0].string.strip(), parseList(tag.ul))

but when I try to call it like this:

myCL = CatList()
myList = myCL.parseList(myCL.soup.ul)

I have the following error:

parseList() takes exactly 1 argument (2 given) 

I tried to add self as an argument to the method but when I do that the error I get is the following:

global name 'parseList' is not defined 

not very clear to me how this actually works.

Any hint?

Thanks

like image 998
slwr Avatar asked Feb 15 '12 22:02

slwr


People also ask

How to fix takes 1 positional argument but 2 were given?

To solve this ” Typeerror: takes 1 positional argument but 2 were given ” is by adding self argument for each method inside the class. It will remove the error.

How do you define a function that takes an argument in Python?

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname).

How many arguments can a function take Python?

While a function can only have one argument of variable length of each type, we can combine both types of functions in one argument. If we do, we must ensure that positional arguments come before named arguments and that fixed arguments come before those of variable length.

Does argument order matter in Python?

With keyword arguments, order does not matter. Number does matter, though, since each keyword argument corresponds with each parameter in the function's definition. Default arguments are entirely optional. You can pass in all of them, some of them, or none at all.


1 Answers

You forgot the self argument.

You need to change this line:

def parseList(tag):

with:

def parseList(self, tag):

You also got a global name error, since you're trying to access parseList without self.
While you should to do something like:

self.parseList(item)

inside your method.

To be specific, you need to do that in two lines of your code:

 return [self.parseList(item)

and

 return (tag.contents[0].string.strip(), self.parseList(tag.ul))
like image 159
Rik Poggi Avatar answered Nov 08 '22 01:11

Rik Poggi