Editor

Refactor Inheritance to Composition

Advanced · Refactor · 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

This code uses inheritance, but Robot is NOT a Speaker - it HAS a speaker. Refactor so that Speaker is a separate class with a speak(text) method returning the text string. Robot should take a name and a Speaker in its constructor, storing the speaker. Its say(text) method should print the result of self.speaker.speak(text). Create a Robot('R2D2', Speaker()) and call say('Hello').

class Speaker:
def speak(self, text):
return text
class Robot(Speaker):
def __init__(self, name):
self.name = name
def say(self, text):
print(self.speak(text))
r = Robot('R2D2')
r.say('Hello')

More Composition exercises

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