Dont Understand


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/1/5?curriculum_id=4f89dab3d788890003000096


i dont understand the meaning of this line

self.items_in_cart[product] = price


Replace this line with your 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('rahul')
my_cart.add_item('underwear',46)


#2

items_in_cart is class/member variable, you defined it here:

    """Creates shopping cart objects
    for users of our fine website."""
    items_in_cart = {}

we can access class variable in methods through self, so this

self.items_in_cart[product] = price

adds key value pair to dictionary.


#3

no..
I mean this part
[product] = price
what does it mean ?


#4

it will create a dictionary entry with key product and value price. We can create a dictionary with entries directly:

example = {
    "test": "test"
}

or create a dictionary and then add entries later:

example = {}
example["test"] = "test"

you do the latter. Except then in a class


#5

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