Classes & Objects
18 min
An object bundles state (data) and behavior (methods that act on that data) together — you met the mechanics of this in the Python course's Classes module. This course goes a level further: designing a class around a real responsibility, with multiple methods that collaborate through shared state.
class Inventory:
def __init__(self):
self.items = {} # shared state every method reads/writes
def add_item(self, name, qty):
self.items[name] = self.items.get(name, 0) + qty
return self # returning self enables method chaining
Returning self from add_item lets you chain calls (.add_item(...).add_item(...)) -- the same pattern the exercises in this course use throughout.
Every method that touches self.items is really just a different VIEW
or OPERATION on the same underlying state — that's the point of grouping
them into one class instead of writing free-floating functions that each
take an items dict as an argument. The object owns its data, and every
interaction with that data goes through a method, giving you one place
to look when you need to understand (or change) how inventory tracking
actually works.
def total_items(self):
return sum(self.items.values())
Given the `Inventory` class below, implement `total_items(self)`, returning the sum of all item quantities currently stored.
Implement `remove_item(self, name, qty)`: if there's enough of `name` in stock, subtract `qty` and return True; otherwise leave the inventory unchanged and return False.
What's the core idea of object-oriented programming's 'object'?
You can design a class where multiple methods collaborate through shared instance state, each representing one operation on that state.