Editor

Build a Computer with Composition

Beginner · 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 a class CPU with a method process() that returns 'Processing data...'. Create a class Computer whose __init__ takes a cpu parameter and stores it as self.cpu. Add a method run() that returns the result of self.cpu.process(). Create a Computer with a CPU and print the result of run().

# Create CPU class
# Create Computer class using composition
# Create and test

More Composition exercises

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