It's not all animals and fruits


#1



please see the last 2 lines of my code.
my_cart = ShoppingCart("Berry")
my_cart.add_item("Berry", 1.0)

You see,I put Berry in my_cart, then i use add_item to add Berry.
Actually it should print"Berry is already in the cart",
but it print "Berry added".

What happend???


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("Berry")
my_cart.add_item("Berry", 1.0)


#2

When you calling my_cart = ShoppingCart("Berry") you assign "Berry" to customer name, look carefully init() method. You need to call mycart.add_item("Berry", 1.0) second time and then you will see what you expect))


#3

oh,thank you very much. now i understand.


#4

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