HST2:面向对象编程实验室创建一个名为ShoppingCart的类。
创建一个不带参数的构造函数,并将total属性设置为零,并初始化一个名为items的空dict属性。
创建一个需要item_name、quantity和price参数的方法add_item。此方法应将所添加项目的成本添加到total的当前值中。它还应该向条目dict添加一个条目,以便键是item_name,值是条目的数量。
创建一个需要与add_item类似的参数的方法remove_item。它应该删除已添加到购物车中且不是必需的项目。此方法应从当前总计中扣除已删除项目的成本,并相应地更新项目字典。
如果要删除的项目数量超过购物车中该项目的当前数量,则假设要删除该项目的所有条目。
创建一个方法checkout,该方法接受cash_paid并返回付款的余额的值。如果cash_paid不足以覆盖总和,则返回“现金支付不够”。
创建一个名为Shop的类,该类有一个不带参数的构造函数,并将一个名为quantity的属性初始化为100。
确保商店继承自ShoppingCart。
在Shop类中,重写remove_item方法,这样在不带参数的情况下调用Shop的remove_item会将数量减1。
# OOP Lab
class ShoppingCart(object):
def __init__(self):
total = 0
item = {}
self.total = total
self.item = item
def add_item(item_name, quantity, price):
cost = quantity * price
self.total += cost
self.item = {"item_name":quantity}
def remove_item(item_name,quantity,price):
cost = quantity * cost
self.total -= cost
for i in self.item:
if quantity > self.item[i]:
del self.item["item_name"]
def checkout(cash_paid):
if cash_paid < self.total:
return "Cash paid not enough"
class Shop(ShoppingCart):
def __init__(self):
quantity = 100
self.quantity = quantity
def remove_item():
self.quantity -= 1
#! Error State the following: my add_item is having four argument instead of three each time i run this code:
请帮助我需要这个代码,我是新的python,我将感谢任何编程天使在python拯救我现在。
发布于 2017-05-28 17:36:42
试试这个,它应该会很好地工作:
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.total += quantity * price
if type(item_name) == str and quantity > 0:
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
if quantity >= self.items[item_name] and quantity >= 1:
items_cost = price * self.items[item_name]
self.total -= items_cost
del self.items[item_name]
else:
self.total -= quantity * price
self.items[item_name] -= quantity
def checkout(self, cash_paid):
balance = 0
if cash_paid < self.total:
return "Cash paid not enough"
balance = cash_paid - self.total
return balance
class Shop(ShoppingCart):
def __init__(self):
self.quantity = 100
def remove_item(self):
self.quantity -= 1发布于 2017-03-12 05:49:11
类方法应该接受self作为第一个参数,例如
def add_item(self, item_name, quantity, price):而不是
def add_item(item_name, quantity, price):传递的“第4个参数”隐式为self,这就是为什么参数的数量比您预期的多一个的原因。
https://stackoverflow.com/questions/42741040
复制相似问题