Understanding Class Composition
Introduction: The “Has-a” Relationship
Welcome to Objects Composition in Python. We are beginning Unit 1 of 4, so we are at the start of our work with composition in this course. In earlier courses, we defined classes, initialized instance attributes, and let objects interact through methods. Now we will take the next step: one object will store another object. This is a has-a relationship: a Car has an Engine. We will first build the engine, then place it inside each car, and finally reach the stored object with chained dot notation.
Build the Component Class: Engine
Let us begin with the smaller object. We will call this object a component because it will become a part of another object. The Engine class stores horsepower and provides a method for starting the engine.
The constructor receives a horsepower value and saves it in self.horsepower. As you may recall, self refers to the particular object being initialized, so every Engine object can have its own horsepower. The start() method reads that attribute and returns a formatted message. It returns a value instead of printing, which lets another part of the program decide how to use the message.
Build the Composite Class: Car
Now that we have an Engine class, we can build a larger object that contains one. We will call Car a composite class because its objects are made from multiple parts.
The constructor stores the car’s model in self.model. The important line is self.engine = Engine(horsepower). First, Engine(horsepower) creates a new Engine object. Then, the assignment stores that object in the car’s engine attribute. The car does not become an engine. Instead, the Car object keeps an Engine object as one of its attributes.
The following object diagram shows how the engine attribute connects the composite object to its component.

