เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การเขียน non-public method

ในบทเรียน เราได้เรียนรู้วิธีเพิ่มฟังก์ชันการทำงานให้กับคลาสโดยใช้ non-public method การกำหนดเมธอดเป็น non-public เป็นการส่งสัญญาณให้ผู้ใช้ทราบว่าเมธอดนั้นมีไว้สำหรับใช้งานภายในแพ็กเกจเท่านั้น

ในแบบฝึกหัดนี้ คุณจะกำหนด non-public method สำหรับนับจำนวนคำ เพื่อให้คลาสนำไปใช้งานต่อได้

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

หลักการวิศวกรรมซอฟต์แวร์ใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • Counter จากไลบรารี collections และฟังก์ชัน tokenize() ถูกโหลดเข้ามาในสภาพแวดล้อมแล้ว
  • เพิ่มเมธอดชื่อ count_words ในรูปแบบ non-public method
  • กำหนดให้ non-public method นี้ทำหน้าที่นับเนื้อหาใน attribute tokens โดยใช้ Counter()
  • นำฟังก์ชันใหม่นี้ไปใช้ใน __init__ method

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด