Delegating Component Behavior
Introduction
Welcome back to Object Composition in Python. We are now beginning Unit 2 of 4, so we have completed the first step of composition and are ready to make our composite objects easier to use. In the previous unit, we stored an Engine inside a Car and reached it with car.engine.start(). That approach works, but it requires the caller to know how the car is built. Today, we will use delegation: the Car will provide its own methods and quietly ask its components to perform the work.
Delegate a Component Method and Add Context
Delegation begins when a composite method calls a method belonging to one of its components. The Car does not need to repeat the engine’s starting logic. Instead, it asks the stored Engine to start, then adds the car’s model to the returned message.
The expression self.engine.start() reaches the component and calls its method. The Car then combines that result with self.model. Callers can now use car.start() instead of knowing that an engine is stored in car.engine.
Forward a Component’s Value Through the Composite
A composite can also forward a value from one of its components. The method below returns the engine’s horsepower without requiring callers to use chained dot notation. Notice that horsepower is a method on Car but an attribute on Engine. These names can be the same because they belong to different objects.
When car.horsepower() runs, the Car looks inside itself, reaches its engine, reads the engine’s horsepower attribute, and returns that value. The caller only needs to understand the Car interface.
This protects the rest of the program from the component’s location. If we later change how the car stores its engine, callers can continue using car.horsepower().
