Functions and Objects · Objects · lesson 7 of 10
Methods and state
about 14 minutes · free · runs in your browser
Objects that change over time
The point of an object is that it remembers things between calls:
class Basket:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def count(self):
return len(self.items)
Note self.items = [] inside __init__ rather than at the class level. A list defined
directly in the class body is shared by every instance — the same trap as a mutable
default argument, in a different costume.
Your turn: write a Basket class with add(item), remove(item) (which ignores
items that are not there), and total() returning how many items it holds.
You start from this, and edit it in the browser:
class Basket:
def __init__(self):
# Start with an empty list of items.
pass
def add(self, item):
pass
def remove(self, item):
pass
def total(self):
pass