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):

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(  # Output: Opening as a text file

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

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!