2012-02-15 54 views
7

我有這樣的方法在一個類蟒蛇:功能恰恰1個參數(2給出)

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) 

我嘗試添加自作爲參數的方法,但是當我這樣做,我得到的錯誤是:

global name 'parseList' is not defined 

對我來說不是很清楚這個實際上是如何工作的。

任何提示?

感謝

回答

18

你忘了self說法。

你需要改變這一行:

def parseList(tag): 

有:

def parseList(self, tag): 

您也有一個全球性的名稱錯誤,因爲你試圖訪問parseListself
雖然你不應該做這樣的事情:

self.parseList(item) 

你的方法裏面。

具體而言,你需要做的是,在兩行代碼的:

return [self.parseList(item) 

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

謝謝,但正如我說這是我的嘗試,然後我得到: 全局名'parseList'未定義 – lorussian 2012-02-15 22:27:30

+2

遞歸調用它,你會寫「self.parselist(tag.ul)」 – 2012-02-15 22:30:01

+0

@silviolor是否將「self」添加到函數聲明和調用中?作爲聲明中的第一個參數,當您調用它時將其作爲「self.parse ...」? – 2012-02-15 22:34:53

相關問題