시작하기무료로 시작하기

비공개 메서드 작성하기

이번 레슨에서는 비공개 메서드를 사용해 클래스에 기능을 추가하는 방법을 배웠어요. 메서드를 비공개로 정의하면, 패키지 내부에서만 사용해야 한다는 뜻을 사용자에게 전달할 수 있어요.

이 연습 문제에서는 클래스가 단어 수를 셀 때 활용할 비공개 메서드를 정의해 보겠습니다.

이 연습은 강의의 일부입니다

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)
코드 편집 및 실행