File Opening with Polymorphism

Define a class File with a method open(). Implement child classes TextFile and CsvFile that override the open() method to open the file in their respective modes.

Example 1:

Input: TextFile
Output: "Opening as a text file"

Example 2:

Input: CsvFile
Output: "Opening as a CSV file"

Override the open() method in each subclass to return the respective file opening method.

class File:
    def open(self):
        pass

class TextFile(File):
    def open(self):
        return "Opening as a text file"

class CsvFile(File):
    def open(self):
        return "Opening as a CSV file"

# Test the classes
text_file = TextFile()
print(text_file.open())  # Output: Opening as a text file

csv_file = CsvFile()
print(csv_file.open())  # Output: Opening as a CSV file

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!