Can't find the answer in the forum, please help!


#1



I don't even know what this error means. Can someone explain it to me and tell me what's wrong with my code?
Thanks in advance!
Here is the error:
Oops, try again. It looks like my_cart isn't an instance of the ShoppingCart class.


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("TheFatBoyArroundTheCorner")
            my_cart.add_item("Pancakes", 16)


#2

well, a class is like a blue-print. Its a design of something. Then the instance is the actual building

Lets say the house you live in, before it was build a blue-print was made (class) and the house you now live in is the instance.

so first you need to create the class:

class example(object):
     # class content

then after the class, we can create the instance:

class Example(object):
     # class content

example = Example()

you created the instance inside the class, that can't be. You don't start building your house (class instance, my_cart) before you finished the blue print (class, ShoppingCart)


#3

So, I've just got the my_cart statements outside the class and it worked! Thank you for the nice explanetion, it is really good! Helped me understand the classes!


#4

I modified the answer a little bit (the last line) because i thought i could do it even better, but good that my original answer already solved the problem and helped improve your understanding :slight_smile:


#5

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