Python Composition: Classes Inside Classes
Composition is a class holding another class as an attribute. The outer class uses the inner class to do part of its job.
An engine on its own
Engine has one job. Its start method returns a short message.
class Engine:
def start(self):
return "Engine started"
engine = Engine()
print(engine.start())A car holds an engine
Car stores an Engine in __init__. The engine is ready before the car moves.
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine()
car = Car()
print(car.engine.start())The car uses its engine
Car start calls the held engine. The car adds its own message after that call.
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
return self.engine.start() + " - Car ready"
car = Car()
print(car.start())Example
class Engine:
def __init__(self, size):
self.size = size
def start(self):
return "Engine " + str(self.size) + " started"
class Car:
def __init__(self, model, size):
self.model = model
self.engine = Engine(size)
def start(self):
print(self.model + ": " + self.engine.start())
def drive(self):
print(self.model + " is moving")
car = Car("Swift", 2)
car.start()
car.drive()
print(car.engine.size)Key points
- Composition: one class holding another class as an attribute
- Use self.engine = Engine() inside __init__ to hold the part
- The outer class calls the inner object by its attribute name
- The inner class keeps its own data and its own methods
- Composition suits a part. A car has an engine, so a car holds one.
- A held object can be swapped for a different one later
In this example, Engine stores a size and its start method names that size. Car stores a model and an Engine built from the size. The start method prints the model with the engine message. The drive method prints a moving message. The last line prints the engine size, so the held engine is visible inside the car.
Note
Composition differs from inheritance. Holding is not extending.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does self.engine = Engine() do inside Car?