การเขียน 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)