• 面向对象的购物车ver1.0


    
    userinfo文件内存放管理员和顾客登录账户
    jack|222|Admin
    mary|111|Customer
    
    
    #!/usr/bin/env python 
    # -*- coding:utf-8 -*-
    # 开发团队: 奶豆的小铺
    # 开发人员: bcz
    # 开发时间: 2020/12/8 19:58
    
    import pickle
    import os
    import sys
    
    
    Base_Dir = os.path.dirname(os.path.dirname(__file__))
    project_dir = os.path.dirname(__file__)
    class Goods():
        '''商品'''
        def __init__(self,name,price,num):
            self.name = name
            self.price = price
            self.num = num
    
        def __str__(self):
            return self.name
    
    
    
    #商店管理员
    class Admin():
        opt_list = [("创建商品", 'create_goods'),
                    ("查看所有商品", 'show_all_goods'),
                    ('退出', 'exit')
                    ]
        def __init__(self,name):
            self.name = name
    
        def create_goods(self):
            '''创建商品'''
            name = input('请输入商品名称: ')
            price = float(input('请输入商品价格: '))
            num = int(input('请输入商品数量: '))
            goods_obj = Goods(name,price,num)
            with open('goods_list_info','ab') as f:
                pickle.dump(goods_obj,f)
            print(f'{goods_obj}商品创建成功')
    
    
        def create_customer(self):
            '''创建顾客'''
            pass
    
    
        def show_all_goods(self):
            '''查看所有商品'''
            with open('goods_list_info','rb') as f:
                count = 0
                while True:
                    try:
                        count +=1
                        goods_obj = pickle.load(f)
                        print(f'商品序号:{count},商品名称:{goods_obj.name},商品价格:{goods_obj.price},商品数量:{goods_obj.num}')
                    except EOFError:
                        print('还没有商品,请先添加商品')
                        break
    
    
    
    
    
        def show_customer_goods(self):
            '''查看顾客购买商品情况'''
    
    
        def exit(self):
            exit('欢迎下次使用')
    
    
    
    #顾客类
    class Customer():
    
        opt_list = [("购买商品", 'select_goods'),
                    ("退商品", 'return_goods'),
                    ('退出', 'exit')
                    ]
    
        def __init__(self, salary_all_money):
            self.salary_all_money = salary_all_money
            self.shopping_car = []
    
    
    
        #购买商品
        def select_goods(self):
            #现打印所有商品
            with open('goods_list_info','rb') as f:
                count = 0
                while True:
                    try:
                        count +=1
                        goods_obj = pickle.load(f)
                        print(f'商品序号:{count},商品名称:{goods_obj.name},商品价格:{goods_obj.price},商品数量:{goods_obj.num}')
                    except EOFError:
                        break
            number_goods = int(input('请输入你选择的商品的序号:  '))
            num_goods = int(input('请输入购买该商品的数量: '))
            with open('goods_list_info', 'rb') as f:
                count1 = 0
                while True:
                    try:
                        count1 += 1
                        goods_obj = pickle.load(f)
                        goods_obj.shop_num = 0
                        if count1 == number_goods:#选中该商品
                            if num_goods <=goods_obj.num and goods_obj.price* num_goods<=self.salary_all_money:
                                #如果购物车为空
                                if len(self.shopping_car) == 0:
                                    goods_obj.shop_num = num_goods
                                    self.shopping_car.append([goods_obj.name,goods_obj.shop_num,goods_obj.price])
    
                                else:
                                    for item in self.shopping_car:
                                        if goods_obj.name == item[0]:
                                            self.shopping_car.remove(item)
                                            goods_obj.shop_num = item[1]
                                            goods_obj.shop_num += num_goods
                                            self.shopping_car.append([goods_obj.name,goods_obj.shop_num,goods_obj.price])
                                            break
    
                                        else:
                                            goods_obj.shop_num = num_goods
                                            self.shopping_car.append([goods_obj.name,goods_obj.shop_num,goods_obj.price])
                                            break
                                print(self.shopping_car)
                                print(f'购买数量{goods_obj.shop_num}')
                                print(f'您选择了{goods_obj.name}商品,购买了{goods_obj.shop_num}个')
                                break  # 选定了商品就可以直接退出了
                            else:
                                print('该商品没有那么多')
                    except EOFError:
                    # print('还没有商品,请先添加商品')
                        break
    
    
    
    
        def return_goods(self):
            '''退商品'''
    
            # #循环自己的购物车,选择自己想退的商品然后从新pickle商品清单
            goods_name_return = input('请输入你想退的商品名称: ')
            for index,item in enumerate(self.shopping_car,1):
                if item[0] == goods_name_return:
                    number_return = int(input('请输入你想退的数量: '))
                    if number_return <= item[1]:
                        self.shopping_car.remove(item)
                        item[1] -= number_return
                        self.shopping_car.append([item[0],item[1],item[2]])
                        print('退货成功')
                        break
                    else:
                        print('你没有购买那么多该商品,退货不成功: ')
                        break
                else:
                    print('你没有购买该商品: ')
                    break
    
    
        #退出会显示该顾客所购商品信息
        def exit(self):
            print('购买商品如下》》》:')
            #shopping_car = [{'iphone':12},{'ipad':9},{'ipone':11}]
            shop_money = 0
            for index, item in enumerate(self.shopping_car, 1):
                print(f'商品序号:{index},商品名称:{item[0]},购买数量:{item[1]}')
                shop_money += item[2]*item[1]
            print(f'共计消费:{shop_money}')
            exit('欢迎下次光临......')
    
    
    
    def login():
        name = input('请输入用户名: ')
        pwd = input('请输入密码: ')
        with open('userinfo',encoding = 'utf-8')as f:
            while True:
                try:
                    for line in f:
                        user,pawd,identify = line.strip().split("|")
    
                        if user == name and pawd == pwd:
                            return {'name':name,'result':True,'id':identify}
                    else:
                        return {'result':False,'name':name,'id':identify}
                except EOFError:
                    break
    
    
    res = login()
    if res['result']:
        print(f"{res['name']}登录成功")
        if hasattr(sys.modules[__name__], res['id']):
            cls = getattr(sys.modules[__name__], res['id'])
            print(res['id'])
            if cls == Admin:
                obj = Admin(res['name'])
                while True:  # 管理员对象可以循环选择进行操作
                    # 循环列举中管理员具有的方法
                    for index, item in enumerate(obj.opt_list, 1):
                        print(index, item[0])
                    func_str = obj.opt_list[int(input('请输入你选择的序号: ')) - 1][1]
                    if hasattr(obj, func_str):
                        getattr(obj, func_str)()
            elif cls == Customer:
                for item in os.listdir(project_dir):
                    if item == 'goods_list_info':
                        salary_all_money = float(input('请输入工资总额: '))
                        obj = Customer(salary_all_money)
                        while True:
                            for index, item in enumerate(obj.opt_list, 1):
                                print(index, item[0])
                            func_str = obj.opt_list[int(input('请输入你选择的序号: ')) - 1][1]
                            if hasattr(obj, func_str):
                                getattr(obj, func_str)()
                else:
                    print('商品列表为空,请先以管理员身份登录创建商品。')
    
    else:
        print(f'{res["name"]}登录失败')
    
  • 相关阅读:
    全程软件测试_项目启动
    全程软件测试_规范测试过程
    python_json常用的方法
    python_eval的用法
    python_判断字符串编码的方法
    python_Notepad++编码集的说明
    python_编码集的介绍
    初识HTML
    mysql学习目录
    python学习目录
  • 原文地址:https://www.cnblogs.com/lihuafeng/p/14122905.html
Copyright © 2020-2023  润新知