Editor

Predict the Output: Swapping Components

Intermediate · Predict the output · 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

Read the code carefully. What will be printed? Pay attention to which logger is used in each case.

class FileLogger:
def log(self, msg):
return f'FILE: {msg}'
class ConsoleLogger:
def log(self, msg):
return f'CONSOLE: {msg}'
class App:
def __init__(self, logger):
self.logger = logger
def do_work(self):
return self.logger.log('Task done')
app1 = App(FileLogger())
app2 = App(ConsoleLogger())
print(app1.do_work())
print(app2.do_work())

More Composition exercises

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