python06

python基础 (v3.6.6)
day06

1. 毕业设计

     ***************** 毕业设计 ***************************
     练习:实现一个商品管理的程序。(建议分 展示层,业务逻辑层,数据访问层 进行代码的编写)
     输入:
     1 --> 添加商品
     2 --> 删除指定商品
     3 --> 查看指定商品
     4 ---> 修改商品的价格,或数量
     5 --> 按商品价格,降序输出
     6 --> 按商品价格,升序输出
     7 --> 按商品数量,降序输出
     8 --> 按商品数量,升序输出
     all --> 输出系统的所有商品
     0 -- > 退出系统

     1、添加商品:
          商品的名称:xxx  商品如果已经存在的话,提示该商品已经存在
          商品的数量:xxxx 数量只能为大于0的整数
          商品的价格:xxx,价格只能为大于0的整数或小数(精确到小数点后两位)
     2、删除商品:
          输入商品名称:Mate 20
              如果输入的商品名称不存在,要提示不存在
     3、查看商品信息,则以json的输出指定商品信息,或按类似以下格式输出
      Mate 20:
          价格:xxx
         数量:xxx
     如果用户输入all,则以json的格式输出所有商品的信息,或按类似以下格式输出
     Mate 20:
     价格:xxx
     数量:xxx

     ------------------------------------
     思路:

     数据访问层: goods.py
     业务逻辑层: 
          逻辑判断: logicService.py
          排序: sortService.py
          业务控制层: controlService.py
     展示层: mainTest.py

     业务调用顺序:
          goods.py → logicService.py
          goods.py → sortService.py
          logicService.py → controlService.py
          sortService.py → controlService.py
          controlService.py → mainTest.py

       或:goods.py → logicService.py → sortService.py → controlService.py → mainTest.py
          可减少实例化次数

-----------------------------------

## 以下为具体代码:


######### goods.py #############################################


import json,traceback

class GoodsSys():
    def __init__(self):
        self.filename = "goods.json"
        self.encoding = "utf-8"

    # 查询所有商品
    def getAllGoods(self):
        with open(self.filename,"r",encoding=self.encoding) as f:
            # 列表形式获取商品信息
            res = f.readlines()
            if len(res) == 0:
                return False
            else:
                return res

    # 查询指定商品
    def getPointGoods(self,goodsname):
        res = self.getAllGoods()
        # for-else:for循环正常结束才会执行else,for循环中途结束,else不执行
        for line in res:
            goods = json.loads(line)
            if goodsname in goods:
                # 注意:return之后,就会跳出循环了
                return goods
        else:
            # 如果不存在,返回False
            return False

    # 保存商品
    def saveGoods(self,goodsname,num,price):
        goods = {goodsname:{"数量":num,"价格":float("%0.2f"%price)}}
        try:
            with open(self.filename,"a+",encoding=self.encoding) as f:
                # 字典转字符串后,写入文件
                f.write(json.dumps(goods,ensure_ascii=False)+"\n")
            return True
        except:
            print(traceback.format_exc())
            return False

    # 删除商品:先读取,再写入
    def delGoods(self,goodsname):
        res = self.getAllGoods()
        # print(res)
        try:
            # w是覆盖写入模式
            with open(self.filename,"w+",encoding=self.encoding) as f:
                for line in res:
                    # print(line,type(line))
                    # 将商品数据的字符串转换成字典格式
                    goods = json.loads(line)
                    if goodsname in goods:
                        continue
                    else:
                        f.write(line)
            return  True
        except:
            print(traceback.format_exc())
            return  False

    # 修改商品
    def modGoods(self,goodsname,num = None,price = None):
        res = self.getAllGoods()
        # print(res)
        try:
            with open(self.filename,"w",encoding=self.encoding) as f:
                # 修改商品数量
                if num != None:
                    for line in res:
                        # 字符串转成字典
                        goods = json.loads(line)
                        if goodsname in goods:
                            goods[goodsname]["数量"] = int(num)
                            f.write(json.dumps(goods,ensure_ascii=False) + "\n")
                        else:
                            f.write(line)
                # 修改商品价格
                else:
                    for line in res:
                        # 字符串转成字典
                        goods = json.loads(line)
                        if goodsname in goods:
                            goods[goodsname]["价格"] = float("%0.2f"%price)
                            f.write(json.dumps(goods,ensure_ascii=False) + "\n")
                        else:
                            f.write(line)
            return  True
        except:
            print(traceback.format_exc())
            return False

if __name__ == "__main__":
    g = GoodsSys()
    g.saveGoods("橘子",10,60)
    g.saveGoods("香蕉",5,5)
    g.saveGoods("苹果",15,16)
    g.saveGoods("桃子",12,5.3)

    # g.delGoods("苹果")

    # g.modGoods("苹果",num=6006)
    # g.modGoods("苹果",price=16)

    # print(g.getPointGoods("苹果"))

########### logicService.py ####################################

from goods import GoodsSys

class LogicService():
    def __init__(self):
        self.g = GoodsSys()

    # 判断用户输入的内容是否为空
    def judgeNone(self,value):
        if len(value) == 0:
            return False
        else:
            return True

    # 判断商品名是否存在
    def judgeExistGoods(self,goodsname):
        res = self.g.getPointGoods(goodsname)
        if res == False:
            # 如果不存在,返回False
            return False
        else:
            return res

    # 判断用户输入的数据是否为大于0的整数
    def judgeInt(self,num):
        # 判断字符串是否由纯数字组成
        if num.isdigit() == True:
            if int(num) > 0:
                # 如果是大于0的整数,则返回True
                return True
            else:
                return False
        else:
            return False

    # 判断用户输入的数据是否为大于0的小数
    def judgeFloat(self,num):
        # 判断字符串是否由纯数字组成
        res = num.split(".")
        if len(res) == 2:
            for i in res:
                if not i.isdigit():
                    return False
            # 如果上面for循环遍历结束还没返回结果,就继续执行下面的语句
            return True
        else:
            return False

if __name__ == "__main__":
    l = LogicService()
    # print(l.judgeNone(""))
    # print(l.judgeExistGoods("苹果"))
    # print(l.judgeInt("123"))
    # print(l.judgeFloat("3.14"))


############## sortService.py ##########################

from goods import GoodsSys
import json
from jsonpath import jsonpath

class SortService():
        def __init__(self):
            self.g = GoodsSys()

        # 按商品价格降序
        def descPrice(self):
            res = self.g.getAllGoods()
            list1 = []
            for line in res:
                list1.append(json.loads(line))
            # 对列表中的字典按价格降序排列
            list1.sort(key=lambda goods:jsonpath(goods,"$..价格"),reverse=True)
            # print(list1)
            return list1

        # 按商品价格升序
        def ascPrice(self):
            res = self.g.getAllGoods()
            list1 = []
            for line in res:
                list1.append(json.loads(line))
            # 对列表中的字典按价格升序排列
            list1.sort(key=lambda goods:jsonpath(goods,"$..价格"))
            # print(list1)
            return list1

        # 按商品数量降序
        def descNum(self):
            res = self.g.getAllGoods()
            list1 = []
            for line in res:
                list1.append(json.loads(line))
            # 对列表中的字典按数量降序排列
            list1.sort(key=lambda goods:jsonpath(goods,"$..数量"),reverse=True)
            # print(list1)
            return list1

        # 按商品数量升序
        def ascNum(self):
            res = self.g.getAllGoods()
            list1 = []
            for line in res:
                list1.append(json.loads(line))
            # 对列表中的字典按数量升序排列
            list1.sort(key=lambda goods:jsonpath(goods,"$..数量"))
            # print(list1)
            return list1

if __name__ == "__main__":
    s = SortService()
    # s.descPrice()
    # s.ascPrice()
    # s.ascNum()


############# controlService.py #########

from logicService import LogicService
from sortService import SortService
import json

class ControlService():
    def __init__(self):
        self.l = LogicService()
        self.s = SortService()

    # 错误提示信息
    def prompt(self,times,msg):
        if times != 0:
            print("亲,%s,您还有%d次机会"%(msg,times))
        else:
            print("输入错误次数过多,系统已返回首页!")

    # 输出单个商品信息
    def getOneGoods(self,res):
        for k,v in res.items():
            print(k + ":")
            times = 1
            for k1,v1 in v.items():
                if times == 1:
                    print("\t" + k1 + ":" + str(v1))
                else:
                    print("\t" + k1 + ":" + "%0.2f"%v1)
                times += 1

    # 打印多个商品信息
    def getWholeGoods(self,res):
        for goods in res:
            self.getOneGoods(goods)

########################################

    # 添加商品
    def addGoods(self):

        times1 = 3
        while times1 > 0:
            # 提示用户输入商品名称
            goodsname = input("请输入商品名称,退出请按q/Q : ")
            if goodsname == "q" or goodsname == "Q":
                # 正常退出
                return 0

            # 判断商品名称是否为空
            if not self.l.judgeNone(goodsname):
                times1 -= 1
                self.prompt(times1,"商品名称不能为空")
                if times1 > 0:
                    continue
                else:
                    return 0

            # 判断商品是否存在
            if self.l.judgeExistGoods(goodsname) !=  False:
               times1 -= 1
               self.prompt(times1,"商品 %s 已存在"%goodsname)
               if times1 > 0:
                   continue
               else:
                   return 0
            # 退出循环
            break

        # 提示用户输入商品数量
        times2 = 3
        while times2 > 0:
            # 提示用户输入商品数量
            num = input("请输入商品数量,退出请按q/Q : ")
            # 判断用户是否退出
            if num == "q" or num == "Q":
                return 0
            # 判断商品数量是否为空
            if not self.l.judgeNone(num):
                times2 -= 1
                self.prompt(times2,"商品数量不能为空")
                if times2 > 0:
                    continue
                else:
                    return 0

            # 判断数量是否为大于0的整数
            if not self.l.judgeInt(num) :
               times2 -= 1
               self.prompt(times2,"商品数量应该是大于0的整数")
               if times2 > 0:
                   continue
               else:
                   return 0
            # 退出循环
            break

        # 提示用户输入商品价格
        times3 = 3
        while times3 > 0:
            # 提示用户输入商品价格
            price = input("请输入商品价格,退出请按q/Q : ")
            # 判断用户是否退出
            if price == "q" or price == "Q":
                return 0
            # 判断商品价格是否为空
            if not self.l.judgeNone(price):
                times3 -= 1
                self.prompt(times3,"商品价格不能为空")
                if times3 > 0:
                    continue
                else:
                    return 0

            # 判断商品价格是否为大于0的整数或小数
            if not self.l.judgeInt(price) and not self.l.judgeFloat(price):
                times3 -= 1
                self.prompt(times3,"商品价格应该为大于0的整数或小数")
                if times3 > 0:
                    continue
                else:
                    return 0
            break

        # 保存商品
        res = self.l.g.saveGoods(goodsname,int(num),float(price))
        if res:
            print("恭喜您,商品保存成功,信息如下:")
            goods  = self.l.judgeExistGoods(goodsname)
            self.getOneGoods(goods)
        else:
            print("保存失败,详情见日志 run.log")


##################################

    # 删除商品
    def delGoods(self):
        times = 3
        while times > 0:
            goodsname = input("请输入商品名称,退出请按q/Q : ")
            # 判断用户是否退出
            if goodsname == "q" or goodsname == "Q":
                return 0

           # 判断商品名称是否为空
            if not self.l.judgeNone(goodsname):
                times -= 1
                self.prompt(times,"商品名称不能为空")
                if times > 0:
                    continue
                else:
                    return 0

            # 判断商品是否存在
            res = self.l.judgeExistGoods(goodsname)
            if res == False:
                times -= 1
                self.prompt(times,"商品名称不存在")
                if times > 0:
                    continue
                else:
                    return 0
            # 删除商品
            res = self.l.g.delGoods(goodsname)
            if res:
                print("恭喜您,商品删除成功。")
                return 0
            else:
                print("删除失败,详情见日志 run.log")

################################
    # 查看指定商品
    def getGoods(self):
        times = 3
        while times > 0:
            goodsname = input("请输入商品名称,退出请按q/Q : ")
            # 判断用户是否退出
            if goodsname == "q" or goodsname == "Q":
                return 0

           # 判断商品名称是否为空
            if not self.l.judgeNone(goodsname):
                times -= 1
                self.prompt(times,"商品名称不能为空")
                if times > 0:
                    continue
                else:
                    return 0

            # 判断商品是否存在
            res = self.l.judgeExistGoods(goodsname)
            # 如果商品不存在,提示用户继续输入
            if res == False:
                times -= 1
                self.prompt(times,"商品名称不存在")
                if times > 0:
                    continue
                else:
                    return 0
            # 如果商品存在,则显示商品信息
            else:
                # print(res)
                self.getOneGoods(res)
                return 0

###############################
    # 修改商品的价格,或数量

    # 注意函数名不要和别的模块中的相同
    def modifyGoods(self):
        times1 = 3
        while times1 > 0:
            goodsname = input("请输入商品名称,退出请按q/Q : ")
            # 判断用户是否退出
            if goodsname == "q" or goodsname == "Q":
                return 0

           # 判断商品名称是否为空
            if not self.l.judgeNone(goodsname):
                times1 -= 1
                self.prompt(times1,"商品名称不能为空")
                if times1 > 0:
                    continue
                else:
                    return 0

            # 判断商品是否存在
            res = self.l.judgeExistGoods(goodsname)
            # 如果商品不存在,提示用户继续输入
            if res == False:
                times1 -= 1
                self.prompt(times1,"商品名称不存在")
                if times1 > 0:
                    continue
                else:
                    return 0
            # 如果商品存在,则退出循环
            break

        times2 = 3
        while times2 > 0:
            order = input("修改数量请按n,修改价格请按p,退出请按q/Q : ")
            # 判断用户是否退出
            if order == "q" or order == "Q":
                return 0
            if order != "n" and order != "p":
                times2 -= 1
                self.prompt(times2,"您的输入有误,请重新再输")
                continue
            else:
                # 修改商品数量
                if order == "n":
                    # 提示用户输入商品数量
                    num = input("请输入商品数量,退出请按q/Q : ")
                    # 判断用户是否退出
                    if num == "q" or num == "Q":
                        return 0
                    # 判断商品数量是否为空
                    if not self.l.judgeNone(num):
                        times2 -= 1
                        self.prompt(times2,"商品数量不能为空")
                        if times2 > 0:
                            continue
                        else:
                            return 0

                    # 判断数量是否为大于0的整数
                    if not self.l.judgeInt(num) :
                       times2 -= 1
                       self.prompt(times2,"商品数量应该是大于0的整数")
                       if times2 > 0:
                           continue
                       else:
                           return 0
                    # 修改商品数量
                    res = self.l.g.modGoods(goodsname,num=int(num ))
                    if res:
                        print("恭喜您,商品数量修改成功!")
                        goods  = self.l.judgeExistGoods(goodsname)
                        self.getOneGoods(goods)
                    return 0

                # 修改商品价格
                else:
                    # 提示用户输入商品价格
                    times3 = 3
                    while times3 > 0:
                        # 提示用户输入商品价格
                        price = input("请输入商品价格,退出请按q/Q : ")
                        # 判断用户是否退出
                        if price == "q" or price == "Q":
                            return 0
                        # 判断商品价格是否为空
                        if not self.l.judgeNone(price):
                            times3 -= 1
                            self.prompt(times3,"商品价格不能为空")
                            if times3 > 0:
                                continue
                            else:
                                return 0

                        # 判断商品价格是否为大于0的整数或小数
                        if not self.l.judgeInt(price) and not self.l.judgeFloat(price):
                            times3 -= 1
                            self.prompt(times3,"商品价格应该为大于0的整数或小数")
                            if times3 > 0:
                                continue
                            else:
                                return 0

                        # 修改商品价格
                        res = self.l.g.modGoods(goodsname,price=float(price))
                        if res:
                            print("恭喜您,商品价格修改成功!")
                            goods  = self.l.judgeExistGoods(goodsname)
                            self.getOneGoods(goods)
                        return 0

###################################
    # 按商品价格,降序输出
    def descByPrice(self):
        res = self.s.descPrice()
        # print(res)
        # for goods in res:
        #     self.getOneGoods(goods)
        self.getWholeGoods(res)

    # 按商品价格,升序输出
    def ascByPrice(self):
        res = self.s.ascPrice()
        self.getWholeGoods(res)

    # 按商品数量,降序输出
    def descByNum(self):
        res = self.s.descNum()
        self.getWholeGoods(res)

    # 按商品数量,升序输出
    def ascByNum(self):
        res = self.s.ascNum()
        self.getWholeGoods(res)

    # 输出系统的所有商品
    def printAllGoods(self):
        res = self.l.g.getAllGoods()
        if res == False:
            print("系统没有商品,请先添加")
            return 0
        else:
            # print(res)
            list1 = []
            for line in res:
                list1.append(json.loads(line))
            self.getWholeGoods(list1)


if __name__ == "__main__":
    c = ControlService()
    # c.addGoods()
    # c.delGoods()
    # c.getGoods()
    # c.modifyGoods()
    # c.descByPrice()
    # c.ascByPrice()
    # c.descByNum()
    # c.ascByNum()
    c.printAllGoods()


############## mainTest.py  #################################

from controlService import ControlService
class MainTest():
    def __init__(self):
        self.c = ControlService()

    def runTest(self):
        times = 3
        while times > 0:
            print()
            print('''本商品管理系统功能如下:
    1 --> 添加商品
    2 --> 删除指定商品
    3 --> 查看指定商品
    4 ---> 修改商品的价格,或数量
    5 --> 按商品价格,降序输出
    6 --> 按商品价格,升序输出
    7 --> 按商品数量,降序输出
    8 --> 按商品数量,升序输出
    all --> 输出系统的所有商品
    0 -- > 退出系统
''')
            order = input("请输入指令:")
            print()
            if order == "1":
                self.c.addGoods()
            elif order == "2":
                self.c.delGoods()
            elif order == "3":
                self.c.getGoods()
            elif order == "4":
                self.c.modifyGoods()
            elif order == "5":
                self.c.descByPrice()
            elif order == "6":
                self.c.ascByPrice()
            elif order == "7":
                self.c.descByNum()
            elif order == "8":
                self.c.ascByNum()
            elif order == "all":
                self.c.printAllGoods()
            elif order == "0":
                print("程序已退出")
                break
            else:
                times -= 1
                if times > 0:
                    print("您的输入有误,还剩下 %d 次机会\n"%times)
                else:
                    print("您的错误次数过多,系统已退出。")

if __name__ == "__main__":
    m = MainTest()
    m.runTest()

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值