
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:
__init__(self, capacity)storescapacityand starts an emptyitemslist.total_weight()returns the sum of all item weights.add(item): if the item would push the total weight abovecapacity, don't add it and returnFalse. Otherwise add it and returnTrue.names()returns a list of the item names, in the order added.
Item is ready. Complete Backpack:
__init__(self, capacity)storescapacityand starts an emptyitemslist.total_weight()returns the sum of all item weights.add(item): if the item would push the total weight abovecapacity, don't add it and returnFalse. Otherwise add it and returnTrue.names()returns a list of the item names, in the order added.
main.py Python sleeping
Press Run to try your code, then Check to test it.