撰寫非公開方法
在課程中,我們介紹了如何用非公開方法為類別加入功能。將方法定義為非公開,等於告訴使用者這個方法只會在套件內部使用。
在本練習中,你會定義一個非公開方法,讓你的類別用來計算字詞數。
本練習屬於課程
Python 的軟體工程原則
練習說明
- 你的環境已載入
collections裡的Counter,以及函式tokenize()。 - 新增一個名為
count_words的方法,並將它定義為「非公開方法」。 - 讓這個非公開方法使用
Counter()來計算tokens屬性的內容。 - 在
__init__方法中使用你剛新增的函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Document:
def __init__(self, text):
self.text = text
# pre tokenize the document with non-public tokenize method
self.tokens = self._tokenize()
# pre tokenize the document with non-public count_words
self.word_counts = self.____()
def _tokenize(self):
return tokenize(self.text)
# non-public method to tally document's word counts with Counter
def ____(self):
return ____(____.tokens)