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

เพิ่มฟังก์ชันการทำงานให้กับ child class

คุณได้เขียนคลาส SocialMedia ที่รับช่วงฟังก์ชันการทำงานมาจาก Document แล้ว แต่ตอนนี้คลาส SocialMedia ยังไม่มีความสามารถพิเศษที่แตกต่างจาก Document เลย ในแบบฝึกหัดนี้ เราจะเพิ่มฟีเจอร์ให้กับ SocialMedia เพื่อให้เหมาะสำหรับการทำงานกับข้อมูลโซเชียลมีเดีย

สำหรับการอ้างอิง ดูนิยามของ Document ได้ด้านล่าง

class Document:
    # Initialize a new Document instance
    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._count_words()

    def _tokenize(self):
        return tokenize(self.text)

    # Non-public method to tally document's word counts
    def _count_words(self):
        # Use collections.Counter to count the document's tokens
        return Counter(self.tokens)

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

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

ดูคอร์ส

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

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

# Define a SocialMedia class that is a child of the `Document class`
class SocialMedia(Document):
    def __init__(self, text):
        Document.__init__(self, text)
        self.hashtag_counts = self._count_hashtags()
        
    def _count_hashtags(self):
        # Filter attribute so only words starting with '#' remain
        return ____
แก้ไขและรันโค้ด