我是一个新的Python,并没有很好的知识OOD。我完成了以下任务,但我觉得代码不好,我不知道如何改进它。有人能帮我吗?你知道吗
You need to create the foundations of an e-commerce engine for a B2C (business-to-consumer) retailer. You need to have a class for a customer called User, a class for items in inventory called Item, and a shopping cart class called Cart. Items go in Carts, and Users have one Carts. but, multiple items can go into Carts, including more than one of any single item.
代码如下所示:
class User(object):
def __init__(self):
self.__cart = Cart()
def BuyGoods(self, gname, gnum, item):
self.__cart.AddItem(gname, gnum, item)
def ShowMygoods(self):
return self.__cart.ShowCart()
class Cart(object):
def __init__(self):
self.__Goodslist = {}
def AddItem(self,goods,goodsnum, item):
if item.SaleGoods(goods,goodsnum) == 0: #class interaction
try:
self.__Goodslist[goods] += goodsnum
except:
self.__Goodslist.update({goods:goodsnum})
def DelItem(self,goods,goodsnum, item):
try:
self.__Goodslist[goods] -= goodsnum
if self.__Goodslist[goods] < 0:
self.__Goodslist[goods] += goodsnum
print "Warnning:there is only %d %s in Cart" % (self.__Goodslist[goods],goods)
return -1
elif self.__Goodslist[goods] == 0:
self.__Goodslist.pop(goods)
item.AddGoods(goods,goodsnum) #class interaction
return 0
except:
print "Error:there are no %s in Cart" % (goods)
return -1
def ShowCart(self):
return self.__Goodslist
class Item(object):
def __init__(self):
self.__itemdict = {}
#@classmethod
def AddGoods(self,goodsname,goodsnum):
try:
self.__itemdict[goodsname] += goodsnum
except:
self.__itemdict.update({goodsname:goodsnum})
#@classmethod
def SaleGoods(self,goodsname,goodsnum):
try:
self.__itemdict[goodsname] -= goodsnum
if self.__itemdict[goodsname] < 0:
self.__itemdict[goodsname] += goodsnum
print "Warnning:there is only %d %s in Item" % (self.__itemdict[goodsname],goodsname)
return -1
elif self.__itemdict[goodsname] == 0:
self.__itemdict.pop(goodsname)
return 0
except:
print "Error:there are no %s in Item" % (goodsname)
return -1
def ShowItem(self):
return self.__itemdict
if __name__ == '__main__':
item1 = Item()
item1.AddGoods('apple', 10)
item1.AddGoods('pear', 5)
print "item1 have %s" % item1.ShowItem()
item2 = Item()
item2.AddGoods('apple', 10)
print "item2 have %s" % item2.ShowItem()
User1 = User()
User1.BuyGoods('apple', 7, item1)
print "User1 have: %s" % User1.ShowMygoods()
print "item1 have %s" % item1.ShowItem()
目前没有回答
相关问题 更多 >
编程相关推荐