Junior — Middle
Can you give an example of dependency injection for replacing a specific component implementation?
sobes.tech AI
Answer from AI
Dependency injection in Python is often implemented by passing a specific component implementation into the constructor or method of a class, which allows for easy replacement of this implementation when necessary.
Example:
class Database:
def connect(self):
pass
class MySQLDatabase(Database):
def connect(self):
print("Connecting to MySQL")
class MockDatabase(Database):
def connect(self):
print("Connecting to mock database for testing")
class Service:
def __init__(self, db: Database):
self.db = db
def perform(self):
self.db.connect()
# Using with a real database
service = Service(MySQLDatabase())
service.perform() # Outputs: Connecting to MySQL
# Using with a mock object for testing
test_service = Service(MockDatabase())
test_service.perform() # Outputs: Connecting to mock database for testing
This approach allows for easy swapping of component implementations without changing the Service class code.