"Its not all animal and fruits" - Possible Bug


#1

If in this exercise we create another cart like

your_cart = ShoppingCart("Jane")
your_cart.add_item("sweater", 2.0)

and add a method to class ShoppingCart

def print_cart(self):
    print self.items_in_cart

And do something like your_cart.print(cart), all the items from all the carts are printed because dict is a mutable type.

See this link.
https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables

Is it a bug? Please help me understand it.


#2

Hi, @designrunner31812 ,

The ShoppingCart class does not have a method named print, so this will not work ...

your_cart.print(cart)

However, you did define a method named print_cart. So, you can do this, instead ...

your_cart.print_cart()

#3

See this complete code and run it.

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."
def print_cart(self):
    print self.items_in_cart

my_cart = ShoppingCart("Mary")
my_cart.add_item("Jelly", 1.0)
my_cart.add_item("Burger", 3.0)
my_cart.add_item("Cake", 8.0)

your_cart = ShoppingCart("Jane")
your_cart.add_item("sweater", 2.0)

print your_cart.print_cart()
print my_cart.print_cart()

My point is that though the Jane and Mary should have same shopping carts, but calling print_cart on any of them gives combined list. Because items_in_cart dict item is a class variable shared by all the instances.


#4

Hi @designrunner31812 ,

Because items_in_cart dict item is a class variable shared by all the instances.

Agreed. I never did like the fact that for this exercise, items_in_cart was a class variable.