如何改进这个OO Python代码?

时间:2015-09-20 12:02:49

标签: python oop

我是一名新的蟒蛇,并且对OOD不了解。我完成了以下任务,但我觉得代码不好而且我不知道如何改进它。任何人都可以帮助我吗?

  

您需要为B2C(企业对消费者)零售商创建电子商务引擎的基础。您需要为客户提供课程   名为User的商品,名为Item的库存商品类,以及名为Cart的购物车类。物品放入购物车,用户有一个购物车。但是,多件物品可以进入购物车,包括任何一件物品中的多件物品。

代码如下所示:

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()

0 个答案:

没有答案