Aggregation

Aggregation is a weak "has-a" relationship. The container references objects that were created outside it and can exist independently. Destroying the container does not destroy the contained objects.

Composition vs Aggregation

  • Composition (strong): Car creates Engine inside its constructor. Engine has no life outside Car.
  • Aggregation (weak): Library stores Books that were created outside it. Books exist independently of the Library.

Aggregation in Code

class Library:
    def __init__(self, name):
        self.name  = name
        self.books = []  # holds references, not ownership
    def add_book(self, book):
        self.books.append(book)
# Books are created OUTSIDE and then passed in:
b = Book("1984", "Orwell")
lib = Library("City Library")
lib.add_book(b)   # Library holds a reference, not ownership

Independent Lifecycle

lib.remove_book("1984")
print(b.title)  # → 1984  — book still exists!
1984

Removing a book from the library only removes the reference from the list. The Book object itself still exists in memory because bstill references it.

UML Notation

  • Composition: filled diamond ◆ at the container end
  • Aggregation: hollow diamond ◇ at the container end
  • Both have an arrow pointing to the contained class

Your Task

  1. Write class Library: with __init__(self, name) that stores self.name and an empty self.books = []
  2. add_book(self, book): append the book object to self.books
  3. remove_book(self, title): remove the first book whose .title matches
  4. list_titles(self): return a list of strings — each book's title
Section 1/5Composition vs Aggregation

Composition vs Aggregation

Explore this concept

Aggregation

Aggregation is a weak "has-a" relationship. The container references objects that were created outside it and can exist independently. Destroying the container does not destroy the contained objects.

Composition vs Aggregation

  • Composition (strong): Car creates Engine inside its constructor. Engine has no life outside Car.
  • Aggregation (weak): Library stores Books that were created outside it. Books exist independently of the Library.

Output:

Click "Check" to run your code.