Question on classes (Python 2 course)

Hi There,

I am a beginner here and progressing with the course Python 2. A quick question on Classes.
I cant get my head around this code “Its not All Animals and Fruits”. My understanding of the classes in Python is that you can create any object as a separate identity with its arguments. I tried to create two objects using ShoppingCart class, however it appears to add the items to one cart. I would expect two separate objects (carts).

This is what I am getting when run the code
apple added.
banana added.
peach added.
banana is already in the cart.
{‘apple’: 5, ‘peach’: 5, ‘banana’: 5}

Hi @karolp80,

In my opinion, the ShoppingCart class was designed in a strange manner. It contains a class variable named items_in_cart that is shared by all instances of that class. Therefore, if you create multiple instances of the class and add items to one of the instances, that item will appear in all instances of that class. The issue could be remedied by moving the items_in_cart variable initialization to the __init__ method and modifying that statement to be as follows:

    self.items_in_cart = {}

This would make items_in_cart into an instance variable.

Many Thanks for help this works perfect now!

1 Like