Python - Introduction to classes
I ran and tested on my computer’s IDLE.
The dictionary items_in_cart{} is a class-wide member variable.
So, if you “Bobby” has a cart and me “Alice” has a cart, Bobby’s purchases show up in Alice’s cart. This is bad. And I think I need to either be enlightend further or this should be fixed.
I’ll copy the class definition far below.
Witness:
[class definition goes here]
>>> b_cart = ShoppingCart('Bobby')
>>> b_cart.add_item('cucumber',20)
cucumber added.
>>> jj_cart.items_in_cart
{'cucumber': 20}
>>> a_cart = ShoppingCart('Alice')
>>> a_cart.items_in_cart # This is Alice's, not Bobby's cart but Bobby's stuff is in it.
{'cucumber': 20}
Bobby and Alice should not be sharing a single cart. The dictionary should be an instance NOT a member variable.
Instead, under the init definition should be the line:
self.items_in_cart = {} # and the class wide member items_in_cart should be deleted.
Class definition below.
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."