Get startedGet started for free

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.

This exercise is part of the course

Software Engineering Principles in Python

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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)
Edit and Run Code