开始使用免费开始使用

编写非公开方法

在本课中,我们介绍了如何使用非公开方法为类添加功能。将方法定义为非公开,意味着告知用户该方法仅供包内部使用。

在本练习中,您将定义一个非公开方法,供类调用以统计词频。

本练习是课程的一部分

Python 中的软件工程原理

查看课程

练习说明

  • 来自 collectionsCounter 已加载到您的环境中,函数 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)
编辑并运行代码