It's Not All Animals and Fruits


Hello, I would like to ask what is this part of code doing: "self.items_in_cart[product] = price"? I am not sure about it.

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."
            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."
            print product + " is not in the cart."

  1. self refers to the current object, which called the add_item method.
  2. self.items_in_cart refers to its dictionary, which you defined on line 4.
  3. self.items_in_cart[product] = price thus creates a new key-value pair in that dictionary, where the key is product and its value is price.

Hope that helps! :slight_smile: