Shopping Cart Class


#1

Hello, I am a bit confused as to how one of the lines of the code given below works.

What does the line self.items_in_cart[product] = price do? I thought the [ ] should only include numbers for lists. For example, if I have a my_list=[1,2,3,4,5], my_list[1] returns the item at index 1; however, product is a string, not a number. I am thoroughly confused as to how that happens. Any help is appreciated. Thanks!

```python

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."
my_cart = ShoppingCart (“John”)
my_cart.add_item(“orange”, 18)

<do not remove the three backticks above>

#2

Hi @shashank.srikanth,

On the line above the __init__ method header, items_in_cart is initialized as a class variable of dict type (dictionary) by this statement …

  items_in_cart = {}

As a dictionary, that object associates keys with values. With a dict, the keys can be objects from among a wide variety of immutable types, including str (string).

By the way, since it as a class variable, there is only one items_in_cart object that is shared by all objects of ShoppingCart type. Not everyone would agree that this was the most effective way to design the ShoppingCart class, but the author of the exercise chose to do it that way for some reason.


#3

Ah I see. Thank you so much!


#4