非公開メソッドの作成
このレッスンでは、非公開メソッドを使ってクラスに機能を追加する方法を学びました。メソッドを非公開として定義することで、そのメソッドはパッケージ内部でのみ使われるべきだとユーザーに示せます。
この演習では、クラスで単語数を数えるために利用する非公開メソッドを定義します。
この演習はコースの一部です
Pythonで学ぶSoftware Engineeringの原則
演習の手順
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)