Python Compose or Inherit?
Compose or inherit is the choice between holding a class and extending a class. Holding fits a part, while extending fits a special kind.
Holding: a car has an engine
Car holds an Engine as an attribute. The engine is a part of the car.
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine()
car = Car()
print(car.engine.start())Extending: a dog is an animal
Dog extends Animal. It keeps speak() and adds fetch() of its own.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " makes a sound"
class Dog(Animal):
def fetch(self):
return self.name + " fetches the ball"
dog = Dog("Rex")
print(dog.speak())
print(dog.fetch())A held part can be swapped
The car takes a new engine. The car code stays the same.
class Engine:
def __init__(self, kind):
self.kind = kind
def start(self):
return self.kind + " engine started"
class Car:
def __init__(self):
self.engine = Engine("petrol")
def start(self):
return self.engine.start()
car = Car()
print(car.start())
car.engine = Engine("electric")
print(car.start())Example
class Engine:
def __init__(self, kind):
self.kind = kind
def start(self):
return self.kind + " engine started"
class Car:
def __init__(self, model, kind):
self.model = model
self.engine = Engine(kind)
def start(self):
return self.model + ": " + self.engine.start()
class ElectricCar(Car):
def __init__(self, model):
super().__init__(model, "electric")
def charge(self):
return self.model + " is charging"
petrol = Car("Swift", "petrol")
electric = ElectricCar("Volt")
print(petrol.start())
print(electric.start())
print(electric.charge())Key points
- Composition: holding another class as an attribute
- Inheritance: extending a class to make a special kind of it
- Use holding when the thing is a part, like an engine in a car
- Use extending when the thing is a kind, like a dog is an animal
- Ask "has a" for holding and "is a" for extending
- A program can use both. One class can hold a part and extend a parent.
In this example, Car holds an Engine, so each car has an engine part. ElectricCar extends Car, so it is a special kind of car. Its __init__ calls super() with "electric" as the engine kind. The petrol car starts its petrol engine. The electric car starts its electric engine and can charge, which is its own extra method.
Note
Pick holding when in doubt. Holding is easier to change later than extending.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A car holds an engine. A sports car extends a car. Which rule fits?