Last active
April 26, 2024 10:24
-
-
Save 2tony2/dd700c8a190c3d7733bc12b226958ed4 to your computer and use it in GitHub Desktop.
abstract classmethod example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC, abstractmethod | |
class DataSource(ABC): | |
@classmethod | |
@abstractmethod | |
def configure(cls, config): | |
""" | |
Configures database connection parameters. Each subclass must implement this | |
method based on its database type specifications. | |
""" | |
pass | |
@abstractmethod | |
def execute_query(self, query): | |
""" | |
Executes a given query on the database instance. Implementation will vary | |
depending on the database type. | |
""" | |
pass | |
class SQLDataSource(DataSource): | |
connection_params = {} | |
@classmethod | |
def configure(cls, config): | |
cls.connection_params = config | |
return f"Configured SQL database with parameters: {cls.connection_params}" | |
def execute_query(self, query): | |
return f"Executing SQL query: '{query}' with parameters {self.connection_params}" | |
class NoSQLDataSource(DataSource): | |
environment_settings = {} | |
@classmethod | |
def configure(cls, config): | |
cls.environment_settings = config | |
return f"Configured NoSQL database with settings: {cls.environment_settings}" | |
def execute_query(self, query): | |
return f"Executing NoSQL query: '{query}' with settings {self.environment_settings}" | |
# Usage of class methods and instance methods | |
sql_config = {'host': 'localhost', 'port': 5432} | |
print(SQLDataSource.configure(sql_config)) | |
nosql_config = {'environment': 'cloud', 'replication': 'enabled'} | |
print(NoSQLDataSource.configure(nosql_config)) | |
sql_data_source = SQLDataSource() | |
print(sql_data_source.execute_query("SELECT * FROM users")) | |
nosql_data_source = NoSQLDataSource() | |
print(nosql_data_source.execute_query("{find: 'users', filter: {active: true}}")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment