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.
Deze oefening maakt deel uit van de cursus
Software Engineering Principles in Python
Oefeninstructies
Counterfromcollectionshas been loaded into your environment, as well as the functiontokenize().- Add a method named
count_wordsas a non-public method. - Give your non-public method the functionality to count the contents
tokensattribute usingCounter(). - Utilize your new function in the
__init__method.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
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)