It's Not All Animals and Fruits - Explain


Here’s a link to the exercise I am on:

I’m wondering why, in the ‘add_item’ function, they use self.items_in_cart(product) = price. I mean, why is self used first? How come it isn’t just items_in_cart(product) = price.

Here’s the code:

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


It is not a standalone function, to start with. It has to be a method of a class. It’s only by that vector does it gain any instantiable context.

The context is the instance that invokes the method.

class Shopping_Cart(object):
    items_in_cart = {}

my_cart = Shopping_Cart()

my_cart.add_item('flash stick', 13.99)

Because it is the context object. All the instance variables are attributes of the current context object of the invoked method.


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