It's Not All Animals and Fruits


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

I don’t understand a certain line of code in this exersize
The line where it says “self.items_in_cart[product] = price” and also "del self.items_in_cart[product]"
Also, where it says “if not product in self.items_in_cart:”, why can’t you just type items_in_cart, why do you need to type self.items_in_cart.
Can someone explain what this does, I understand the rest of the code.

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("Y")
my_cart.add_item("Egg", 2)

10/18 - Explaining the line that defines price
#2

The self keyword references a variable contained in a class. Because items_in_cart is contained inside a class, it becomes necessary to reference parts of it using .self


#3

Ok. What does making self.items_in_cart[product] = price.
So this adds the product to the cart but what does equaling it to price do.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.