Constructor Injection in Composition
Introduction
Welcome back to Object Composition in Python. We are now beginning Unit 3 of 4 in this course. In the previous lesson, we learned how a composite object can delegate work to its components. Today, we will change how those components enter the composite. Instead of creating an engine inside Car, we will create the engine first and pass it into the car. This opens the door to separate components, shared state, and interchangeable component classes.
Why Pass Parts In?
When a class creates its own components, it controls the entire assembly process. That can be convenient, but it also makes the class less flexible. Passing a component in from outside gives the caller more control over which part the composite uses.
Think of Car as a device with a connection point. The car needs an object that can provide start(), but it does not need to know how that object was built. This design lets us:
- Give different composites different component objects.
- Deliberately share one component between multiple composites.
- Replace a component with another object that supports the same method.
This pattern is often called constructor injection because the component is supplied through the constructor.
Inject a Prebuilt Component into a Composite
Let us refactor the classes from the earlier lessons. Engine still owns its horsepower and still provides start(). The important change is that Car receives an engine parameter instead of creating an engine internally.
The statement self.engine = engine stores the exact object passed to the constructor. Later, self.engine.start() delegates the starting work to that stored component, just as we learned in Unit 2. The difference is that Car no longer decides which engine to create. The caller assembles the parts, while Car coordinates their behavior.
Assemble Independent Composites with Different Components

