Editor

Compose Multiple Abilities

Intermediate · 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 ability classes: Swim with a method action() returning 'swimming', and Climb with a method action() returning 'climbing'. Create a Character class that takes name (str) and abilities (list). Add a method show_abilities() that prints '{name} can: ' followed by each ability's action joined by ', '. Create a Character('Bear', [Swim(), Climb()]) and call show_abilities().

# Create ability classes
# Create Character class
# Create and test

More Composition exercises

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