【问题标题】:python: function takes exactly 1 argument (2 given)python:函数只需要1个参数(给定2个)
【发布时间】:2012-03-07 07:53:51
【问题描述】:

我在课堂上有这个方法

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

但是当我尝试这样称呼它时:

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

我有以下错误:

parseList() takes exactly 1 argument (2 given) 

我尝试将 self 作为参数添加到方法中,但是当我这样做时,我得到的错误如下:

global name 'parseList' is not defined 

我不太清楚这实际上是如何工作的。

有什么提示吗?

谢谢

【问题讨论】:

    标签: python class methods


    【解决方案1】:

    您忘记了 self 参数。

    你需要改变这一行:

    def parseList(tag):
    

    与:

    def parseList(self, tag):
    

    您还遇到了全局名称错误,因为您尝试在没有 self 的情况下访问 parseList
    虽然您应该执行以下操作:

    self.parseList(item)
    

    在你的方法中。

    具体来说,您需要在两行代码中做到这一点:

     return [self.parseList(item)
    

     return (tag.contents[0].string.strip(), self.parseList(tag.ul))
    

    【讨论】:

    • 谢谢,但正如我所说,这是我尝试过的,然后我得到:未定义全局名称'parseList'
    • 递归调用它,你会写“self.parselist(tag.ul)”
    • @silviolor 您是否将“self”添加到函数声明和调用中?作为声明中的第一个参数和调用时的“self.parse...”?
    猜你喜欢
    • 2012-03-04
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多