Code

Has-a: Composition

Big programs are built from small objects that contain other objects. A ship has a crew; a crew has members. This is called composition, and it's the most common way classes work together.

class Sailor:
    def __init__(self, name):
        self.name = name

class Ship:
    def __init__(self, name):
        self.name = name
        self.crew = []          # a list of Sailor objects

    def hire(self, sailor):
        self.crew.append(sailor)

    def roster(self):
        names = []
        for sailor in self.crew:
            names.append(sailor.name)
        return names

The Ship doesn't need to know how a sailor works inside; it just holds sailors and asks them for what it needs (s.name). Each class stays small and focused on one job.

Assignment

Item is ready. Complete Backpack:

  1. __init__(self, capacity) stores capacity and starts an empty items list.
  2. total_weight() returns the sum of all item weights.
  3. add(item): if the item would push the total weight above capacity, don't add it and return False. Otherwise add it and return True.
  4. names() returns a list of the item names, in the order added.