Items_in_cart {} should be an instance, but is a member dictionary, in 11:10 It's Not All

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."
1 Like

Thank you for reporting the problem, we recognise this is a bug, however as it does not prevent users from passing the lesson and this is one of the older courses it is unlikely this bug will be fixed. Thank you for taking the time to inform us though, we would like everything to be fixed just as much as you would! :smiley:

For reference: exercise link