在Python中添加ShoppingCart类、addToCart、itemCount和isEmpty函数
我接到了一个任务,我正在努力完成它。它已经给出了一个事务类和它自己的函数。任务是添加ShoppingCart类,以及它的以下函数:addToCart、removeNextItem、itemCount、isEmpty 事务类已经定义/调用了要添加的类和函数,因此必须遵循事务类的这些要求。 最接近的例子可以在上找到,但仍然有很大的区别 我已经试着添加了下面所需的类/函数,但我觉得还很遥远在Python中添加ShoppingCart类、addToCart、itemCount和isEmpty函数,python,class,cart,Python,Class,Cart,我接到了一个任务,我正在努力完成它。它已经给出了一个事务类和它自己的函数。任务是添加ShoppingCart类,以及它的以下函数:addToCart、removeNextItem、itemCount、isEmpty 事务类已经定义/调用了要添加的类和函数,因此必须遵循事务类的这些要求。 最接近的例子可以在上找到,但仍然有很大的区别 我已经试着添加了下面所需的类/函数,但我觉得还很遥远 class Transaction: # Constructor. Takes a shoppingC
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
班级购物艺术
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()
这似乎是对的,错误到底在哪里?,
def is Empty()
不是一个有效的函数ItemCount不正确addToCart:5+以后的行不确定/不正确def is Empty():完全没有请阅读-总结是,这不是解决志愿者问题的理想方法,而且可能对获得答案起到反作用。请不要将此添加到您的问题中。这里没有太多的问题描述。你能通过编辑问题本身来改进这一点吗?你期望什么样的产出,你得到了什么?你能把这些输出放在问题中的格式化块中吗?