Home > Blockchain >  Create a shopping cart class
Create a shopping cart class

Time:10-16

I'm trying to create a program with "Item" and "Shopping Cart" as 2 separate classes.

Using a "Shopping Cart" I should be able to add/remove/update and get the total cost the items listed in "Items" in the cart, but I'm unsure of how to access the "Items" dictionary and add it to the shopping cart list.

l_items = ({"teddy": {'name': 'Teddy',
                      "desc": "toy",
                      "price": 3.21},
            "sweet": {'name': 'Rolo',
                      "desc": 'chocolate',
                      'price': 1.21}})


class Item:

    def __init__(self, name, desc, price):
        self._name = name
        self._desc = desc
        self._price = price
        self._stock = len(l_items)

    def __repr__(self):
        return self.name


class ShoppingCart:

    def __init__(self, item=[]):
        self._item = item

    def add_item(self, new):
        self._item.append(new)

    def remove_item(self, remove):
        self._item.remove(remove)

    def update_item(self, update):
        pass

    def view(self):
        return self

    def getTotalCost(self):
        total = 0
        for i in self._item:
            total  = i.getTotalCost()

    def reset(self):
        self._item = []

    def isEmpty(self):
        return len(self._items) == 0
 

CodePudding user response:

Please do this first!

As pointed out by @ThierryLathuille, it would be wise of you to rewrite the constructor of the class ShoppingCart, as shown in the code section.

Also, the __repr__ method in the Item class seems incorrect. You probably wanted to return self._name instead of self.name, as in the code you have shared self.name does not exist in the Item class.

Code

class Item:
    ...  # The rest of your class's contents
    def __repr__(self):
        return self._name
class ShoppingCart:
    def __init__(self, item=None):
        if item is None:
            self._item = []
        else:
            self._item = item
    
    ...  # The rest of your class's contents

Note: In your code, doing item=[] in the ShoppingCart constructor's parameter list does not mean that, each time the constructor is called, a new list will be created and set as the default value of the item parameter.

What actually happens is that it will create and (re)use only a single shared instance of the list object across all constructor calls, giving you the behaviour you may not expect, such as the shopping cart list being shared among different users.

Interacting with items and your shopping cart

Now, coming to your question, you could do something like this:

Adding items to your cart

cart = ShoppingCart()  # Creating an instance of shopping cart
for itemType in l_items:
    item = l_items[itemType]  # Getting the dictionary containing the item's data
    itemObject = Item(item['name'], item['desc'], item['price'])  # Creating an instance of Item
    cart.add_item(itemObject)  # Adding the item object to the instance of ShoppingCart

CodePudding user response:

Default values in python act like static variables. There is only one default object created for any number of Method Invocations.

  • Related