Database Connection with Polymorphism

Implement a class Database with a method connect(). Extend this class into MySQLDatabase and PostgreSQLDatabase, each implementing the connect() method appropriately.

Example 1:

Input: MySQLDatabase
Output: "Connecting to MySQL Database"

Example 2:

Input: PostgreSQLDatabase
Output: "Connecting to PostgreSQL Database"

Override the connect() method in each subclass to return the respective connection message.

class Database:
    def connect(self):
        pass

class MySQLDatabase(Database):
    def connect(self):
        return "Connecting to MySQL Database"

class PostgreSQLDatabase(Database):
    def connect(self):
        return "Connecting to PostgreSQL Database"

# Test the classes
mysql_database = MySQLDatabase()
print(mysql_database.connect())  # Output: Connecting to MySQL Database

postgresql_database = PostgreSQLDatabase()
print(postgresql_database.connect())  # Output: Connecting to PostgreSQL Database

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!