Editor

Dependency Injection: Notification System

Advanced · Write the code · from Composition vs Inheritance: Why 'Has-a' Often Beats 'Is-a'

From the lesson: Composition vs Inheritance: Why 'Has-a' Often Beats 'Is-a'

Inheritance is like a family tree. A child inherits traits from their parents, grandparents, and beyond. It's powerful, but sometimes the family tree gets tangled and confusing.

Read the lesson

Create two notifier classes: EmailNotifier with a method send(msg) that returns 'Email: ' + msg, and SMSNotifier with send(msg) returning 'SMS: ' + msg. Create an AlertSystem class that takes a notifier in its constructor. Add a method alert(msg) that prints the result of self.notifier.send(msg). Create two AlertSystems (one with each notifier) and call alert('Server down') on each.

# Create notifier classes
# Create AlertSystem
# Test with both notifiers

More Composition exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz