在Python

时间:2018-04-27 03:07:52

标签: python class cart

我得到了一项任务,我正在努力。它已经提供了一个Transaction Class和它自己的函数。任务是添加ShoppingCart类,并遵循以下函数:addToCart,removeNextItem,itemCount,isEmpty。

事务类已经定义/调用了这些待添加的类和函数,因此必须遵循类事务的这些要求。 最近的例子可以在Python shopping cart add to cart, get total get num items找到,但仍然存在很大差异。

我试图添加下面所需的类/功能,但我觉得它还很遥远。

class Transaction:

    # Constructor. Takes a shoppingCart upon which it will base the transaction.
    def __init__(self, sc):
        self.shoppingCart = sc


    def getTransactionTotal(self):

        itemList = ""
        totalCost = 0.0


        while not self.shoppingCart.isEmpty():


            itemName, costPerItem, quantity = self.shoppingCart.removeNextItem()

            itemList += (str(quantity) + " × " + str(itemName) + "\n")

            totalCost += (costPerItem * quantity)

        return itemList, totalCost


    def isValidTransaction(self):

        return self.shoppingCart.itemCount() > 0

类ShopppingCart

class ShoppingCart(object):
    def __init__(self):
        self.content = dict()



    def addToCart(self, name, price, qty):
        if name not in self.content:
            self.content.update({name: (name, price, qty)})
            return
        for k, v in self.content.get(name).items():
            if k == 'qty':
                total_qty = v.qty + qty
                if total_qty:
                    v.qty = total_qty
                    continue
                #self.remove_item(k)
                self.removeNextItem(k)
            else:
                v[k] = item[k]


     #def remove_item(self, key):
    def removeNextItem(self, key):
        self.content.pop(key)

    def itemCount(self):
       for k, v in self.content.get(name).items():
           total_qty = v.qty + qty
        return total_qty

    def isEmpty()

测试人员功能。

def main():


    sc = ShoppingCart()

    sc.addToCart("Dijon Ketchup", 4.99, 1)
    sc.addToCart("Van Gogh Doodle", 99.99, 1)
    sc.addToCart("Irregularly Shaped Donut", 0.50, 1)

    sc.addToCart("Poodle", 25.00, 3)
    sc.addToCart("Noodle", 0.99, 10)
    sc.addToCart("Yodel", 2.50, 5)


    trans = Transaction(sc)



    itemizedList, total = trans.getTransactionTotal()


    receipt = "Items\n-------------------\n" + itemizedList
    receipt += "\nTotal Cost: $" + str(total) + "\n\n"


    receipt += "Manually tallied total: $"
    manualTotal = 4.99 + 99.99+ 0.5 + (3 * 25) + (10 * 0.99) + (5 * 2.5)


    receipt += str(manualTotal)

    print(receipt)

    #else:
       # print("Your cart is empty.")


if __name__ == "__main__":
    main()

0 个答案:

没有答案