Document Saving with Polymorphism

Define a class Document with a method save(). Implement child classes WordDocument and PdfDocument that override the save() method to save the document in their respective formats.

Example 1:

Input: WordDocument
Output: "Saving as .docx file"

Example 2:

Input: PdfDocument
Output: "Saving as .pdf file"

Override the save() method in each subclass to return the respective saving method.

class Document:
    def save(self):
        pass

class WordDocument(Document):
    def save(self):
        return "Saving as .docx file"

class PdfDocument(Document):
    def save(self):
        return "Saving as .pdf file"

# Test the classes
word_document = WordDocument()
print(word_document.save())  # Output: Saving as .docx file

pdf_document = PdfDocument()
print(pdf_document.save())  # Output: Saving as .pdf file

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!