It's Not All Animals and Fruits - Explain


#1

Here’s a link to the exercise I am on: https://www.codecademy.com/courses/learn-python/lessons/introduction-to-classes/exercises/its-not-all-animals-and-fruits

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


#2

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.


#3

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