Managing Object Collections
Introduction
Welcome back to Object Composition in Python. We are now at Unit 4 of 4, the final unit in this course. In earlier units, we stored one component inside a composite object, delegated behavior to it, and supplied interchangeable components from outside. Now we will expand that idea: one class can store and manage many objects.
As a reminder, here is our Car class:
Each car stores a model and horsepower. Its describe() method returns a formatted string. We will drop the Engine class for now so we can focus on storing a list of Car objects inside another class.
Create an Empty Collection and Add Objects
Now we need a container class that can own several cars. We will call it Garage. Its constructor stores a name and creates an empty list. The list is empty at first because the cars will be added later.
The statement self.cars = [] gives every Garage its own collection. The add() method receives an existing car and appends it to that collection. Each call to Car(...) creates an independent object, and each call to garage.add(...) stores a reference to that object.
The garage now has three cars. This is composition with a collection: the Garage object has many Car objects.
Loop Through the Stored Objects
With the cars stored, the garage can loop through them. We will add a listing() method that asks each car to describe itself. This method prints each returned string directly instead of creating and returning a separate list.
The for loop visits each object in self.cars. During each iteration, car refers to one stored Car object. The expression car.describe() calls that object’s method, and print() displays the returned text.
Because the method prints directly, the caller only needs to write garage.listing().
The order matches the order in which the cars were added.
