LoslegenKostenlos loslegen

Writing a non-public method

In the lesson, we covered how to add functionality to classes using non-public methods. By defining methods as non-public you're signifying to the user that the method is only to be used inside the package.

In this exercise, you will define a non-public method that will be leveraged by your class to count words.

Diese Übung ist Teil des Kurses

Software Engineering Principles in Python

Kurs anzeigen

Anleitung zur Übung

  • Counter from collections has been loaded into your environment, as well as the function tokenize().
  • Add a method named count_words as a non-public method.
  • Give your non-public method the functionality to count the contents tokens attribute using Counter().
  • Utilize your new function in the __init__ method.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

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)
Code bearbeiten und ausführen