编写非公开方法
在本课中,我们介绍了如何使用非公开方法为类添加功能。将方法定义为非公开,意味着告知用户该方法仅供包内部使用。
在本练习中,您将定义一个非公开方法,供类调用以统计词频。
本练习是课程的一部分
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)