python: function takes exactly 1 argument (2 given)

落爺英雄遲暮 提交于 2019-12-18 22:24:22

问题


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


回答1:


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))


来源:https://stackoverflow.com/questions/9302436/python-function-takes-exactly-1-argument-2-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!