In this lesson, you'll get familiar with a new way of linking different classes.
We will cover the following:
- Independent Lifetimes
- Example
Aggregation follows the Has-A model that creates a parent-child relationship between two classes (where one class owns the object of another).
- In aggregation, the lifetime of the owned object does not depend on the lifetime of the owner.
If the owner object gets deleted, the owned object can continue in the program. In aggregation, the parent only contains a reference to the child, which removes the child’s dependency.
You can probably guess from the illustration above that we’ll need object references to implement aggregation.
Let’s take the example of people and their country of origin. Each person is associated with a country, but the country can exist without that person:
class Country:def __init__(self, name=None, population=0):self.name = nameself.population = populationdef printDetails(self):print("Country Name:", self.name)print("Country Population", self.population)class Person:def __init__(self, name, country):self.name = nameself.country = countrydef printDetails(self):print("Person Name:", self.name)self.country.printDetails()c = Country("Wales", 1500)p = Person("Joe", c)p.printDetails()# deletes the object pdel pprint("")c.printDetails()
As we can see, the Country object (`c`) lives on even after we delete the Person object (`p`).This creates a weaker relationship between the two classes.