python实验设计报告----超市管理系统

本文详细描述了一款超市管理系统的开发过程,涉及文件结构、功能模块(管理员登录、商品增删改查、用户注册购买等)、遇到的问题及解决方案,展示了源代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一.项目概述

二.文件结构

三.结果截屏

四.遇到问题和解决措施

五.源代码


一.项目概述

项目介绍

设计题目:超市管理系统。

主要实现功能:管理员登录,增加商品,存储商品,修改商品,显示所有商品,用户注册和登录,查询商品,购买商品。

实现过程:如图1所示。

图1:超市管理系统流程图

.文件结构

总共写了5个文件。

文件一work.py:用户可以输入身份选择作为管理员或普通用户登录。根据不同的身份,系统提供相应的功能。

文件二goods.py:初始化商品对象。

文件三manager.py:定义了一个名为Manager的类,用于实现超市商品管理系统的管理员功能,对超市商品的增删改查等管理操作这个类具有以下主要方法:管理员登录login(),展示管理员功能selectManageCode(),查询并打印所有商品信息queryAllGoods(),添加商品addGoods(),删除商品deleteGoods(),修改商品价格modifyGoods()。

文件四user.py:初始化用户对象。

文件五userfun.py:定义了一个用户功能类,主要用于处理超市系统中普通用户的操作,包括商品查询、购买流程管理等。这个类具有以下主要方法:显示用户功能user_option(),注册新用户register()让用户决定是否进行新用户注册selectRegister(),查询某件商品 findGoodsById(),购买商品添加至购物车buyGoods()。

.结果截屏

图2 

图3 

图4 

图5

.遇到问题和解决措施

问题1:TypeError: 'str' object is not callable

解决措施:在格式化字符串时犯了一个错误。问题在于打印商品列表时忘记添加% 操作符。

问题2:TypeError: 'set' object is not subscriptable

解决措施:当尝试从 self.goodlist 中获取最后一个商品时,报错提示 'set' object is not subscriptable。这是因为在创建 Manager 实例时将 goodlist 初始化为了一个集合(set),而在 Python 中集合是不可通过索引访问其元素的。为了解决这个问题,在初始化 Manager 时传入的是列表(list)而不是集合(set)。

问题3TypeError: must be real number, not str

解决措施:在 queryAllGoods 方法中,当遍历 self.goodlist 并打印商品信息时,错误提示是因为有一个商品的价格不是数字类型而是字符串类型。这可能是因为在添加商品时,尽管已经使用了 try-except 语句来确保输入的商品价格为数字类型,但是在某些情况下,它没有正确地将用户输入转换为浮点数。为了解决这个问题,我再次检查 addGoods 方法中的 goodprice 变量是否始终被成功转换为浮点数。

问题4:TypeError: UserFun.init() takes 1 positional argument but 2 were given

解决措施:在 UserFun 类中定义了两个 __init__ 方法,当实例化 UserFun 类时,Python 不知道该调用哪个初始化方法。同时,第一个 __init__ 方法接收一个参数 goodlist,而第二个 __init__ 方法不接收任何参数。为了解决该问题,需要将这两个初始化方法合并成一个,并确保它能正确处理商品列表和用户列表。

五.源代码

work.py

from goods import Goods
from manager import Manager
from userFun import UserFun


def selectLoginCode():
    prompt = """========================== 欢迎进入大壮超市 ==================================
请输入身份:
1:管理员
2:普通用户
输入其他则出现错误
============================================================================"""
    print(prompt)

    shopGoods = [Goods(1, "雪碧", 1.7), Goods(2, "可乐", 1.7), Goods(3, "芬达", 2.0)]
    code = input("请输入身份:")
    if code == "1":
        manager = Manager(shopGoods)
        isLogin = manager.login()
        if isLogin:
            manager.selectManageCode()
    elif code == "2":
        userFun = UserFun(shopGoods)
        userFun.selectRegister()
    else:
        print("输入错误")

if __name__ == "__main__":
    selectLoginCode()

goods.py

class Goods:
    def __init__(self, id , tname, tprice):
        self.id = id
        self.tname = tname
        self.tprice = tprice

manager.py

from goods import Goods


class Manager:
    def __init__(self, goodlist=None):
        self.goodlist = goodlist

    def login(self):
        """管理员登录"""
        n = 1
        while n <= 3:
            mname = input("请输入管理员姓名:")
            mpwd = input("请输入管理员密码:")
            if mname == "superhero" and mpwd == "666888":
                print("登录成功")
                return True
            if n != 3:
                print("管理员姓名或者密码错误,还剩%d次机会,请重新输入!" % (3 - n))
            n += 1
        print("登录失败")
        return False

    def selectManageCode(self):
        option = """
=============== 请输入功能:================
1:增加商品(商品名称,价格)
2:删除商品(根据商品编码)
3:修改商品(根据商品编码修改价格)
4:展示所有商品
0:退出
=========================================="""
        print(option)
        while True:
            code = input("请输入功能:")
            if code == "1":
                self.addGoods()
            elif code == "2":
                self.deleteGoods()
            elif code == "3":
                self.modifyGoods()
            elif code == "4":
                self.queryAllGoods()
            elif code == "0":
                print("退出系统")
                return
            else:
                print("没有该功能,请重新输入!")

    def queryAllGoods(self):
        """查询所有商品"""
        print("""----------------全部商品-------------------
编号\t\t商品名称\t\t\t价格""")
        for good in self.goodlist:
            print("%d\t\t%s\t\t\t\t%s" % (good.id, good.tname, good.tprice))
        print("------------------------------------------")

    def addGoods(self):
        """添加商品"""
        print("----------------添加商品-------------------")
        # 商品id如何变化
        if len(self.goodlist) == 0:
            id = 1
        else:
            lastGoods = self.goodlist[-1]
            id = lastGoods.id + 1
        # 判断商品是否存在
        goodname = input("请输入商品名称:")
        for good in self.goodlist:
            if good.tname == goodname:
                print("商品已存在")
                return
        # 确保输入的商品价格是数字类型
        while True:
            goodprice = input("请输入商品价格:")
            try:
                gprice = float(goodprice)
                break
            except ValueError:
                print("价格请输入数字类型")
        # 将商品添加到商品列表中
        newgood = Goods(id, goodname, goodprice)
        self.goodlist.append(newgood)

        print("----------------添加成功-------------------")

    def deleteGoods(self):
        """删除商品"""
        print("----------------删除商品-------------------")
        # 对输入的商品id进行判断
        try:
            delId = int(input("请输入商品编号:"))
        except:
            print("删除失败")
            return
        # 遍历每一个商品,获取商品id是否存在,如果存在则删除该商品
        for good in self.goodlist:
            if good.id == delId:
                self.goodlist.remove(good)
                print("删除成功")
                return
        print("删除失败")

    def modifyGoods(self):
        """修改商品价格"""
        print("----------------修改商品-------------------")
        try:
            modId = int(input("请输入商品编号:"))
        except:
            print("修改失败")
            return
        for good in self.goodlist:
            if good.id == modId:
                try:
                    modPrice = float(input("请输入修改后的价格:"))
                except:
                    print("修改失败")
                    return
                good.tprice = modPrice
                print("----------------修改成功-------------------")
                return
        print("修改失败")

user.py

class User:
    def __init__(self, uname, upwd):
        self.uname = uname;
        self.upwd = upwd;

userFun.py

from user import User


class UserFun:
    def __init__(self, goodlist=None):
        self.goodlist = goodlist if goodlist is not None else []
        self.user_list = []

    def user_option(self):
        user_chance = """=============== 请输入功能:================
1:查询商品(根据商品编码查询)
2:购买商品(根据商品编码和数量进行购买)
0:退出
=========================================="""
        print(user_chance)
        while True:
            code = input("请输入功能:")
            if code == "1":
                self.findGoodsById()
            elif code == "2":
                self.buyGoods()
            elif code == "0":
                print("退出系统")
                return
            else:
                print("没有该功能,请重新输入!")

    def register(self):
        """注册新用户"""
        while True:
            new_name = input("请输入新用户姓名:")
            new_pwd = input("请输入新用户密码:")
            re_pwd = input("请再次输入新用户密码以确认:")

            if new_pwd == re_pwd:
                # 创建新用户对象并添加到用户列表中
                new_user = User(new_name, new_pwd)
                self.user_list.append(new_user)
                print("注册成功!即将跳转到功能选择页面")
                self.user_option()
                return
            else:
                print("两次输入的密码不一致,请重新注册!")

    def selectRegister(self):
        prompt = """=================欢迎用户登录==================
1:新用户注册
输入其他则无效
========================================="""
        print(prompt)
        while True:
            code = input("请输入功能:")
            if code == "1":
                self.register()
                return
            else:
                print("输入错误,请重新输入!")

    def findGoodsById(self):
        """根据商品编号查询某一件商品的具体信息"""
        find_id = int(input("请输入要查询的商品编号:"))

        found_goods = None
        for good in self.goodlist:
            if good.id == find_id:
                found_goods = good
                break

        if found_goods:
            print(f"商品信息:编号: {found_goods.id}\t名称: {found_goods.tname}\t价格: {found_goods.tprice}")
        else:
            print("抱歉,没有找到该商品,请重新输入")

    def buyGoods(self):
        shopping_cart = []
        total_price = 0

        while True:
            goods_code = input("请输入要购买的商品编号(输入 q 结束选购):")

            if goods_code.lower() == "q":
                break

            try:
                goods_code = int(goods_code)
                found_goods = None
                for good in self.goodlist:
                    if good.id == goods_code:
                        found_goods = good
                        break

                if not found_goods:
                    print("没有该商品,请重新输入!")
                    continue

                while True:
                    quantity = input(f"{found_goods.tname}购买数量: ")

                    if quantity.lower() == "q":
                        print("已取消购买该商品!")
                        break

                    try:
                        quantity = int(quantity)
                        if quantity <= 0:
                            print("请输入大于0的购买数量!")
                        else:
                            total_price += quantity * found_goods.tprice
                            item_info = {"good": found_goods, "quantity": quantity}
                            shopping_cart.append(item_info)
                            print(
                                f"加入购物车,总价为:{quantity * found_goods.tprice:.2f}")
                            break
                    except ValueError:
                        print("请输入有效的数字作为购买数量!")

            except ValueError:
                print("请输入有效的商品编码!")

        if len(shopping_cart) > 0:
            print("\n您的购物车内容如下:")
            for item in shopping_cart:
                print(f"{item['quantity']} 件 {item['good'].tname},总价:{item['quantity'] * item['good'].tprice:.2f}")

            confirm_purchase = input("确认购买请输入 y,否则请输入 n:")
            if confirm_purchase.lower() == "y":
                print(f"\n购买成功!共购买了以下商品:")
                for item in shopping_cart:
                    print(
                        f"{item['quantity']} 件 {item['good'].tname},总价:{item['quantity'] * item['good'].tprice:.2f}")
                print(f"总金额为:{total_price:.2f}")
            elif confirm_purchase.lower() == "n":
                print("购买操作已取消!")
            else:
                print("无效输入,请重新确认!")
        else:
            print("您未选购任何商品!")

        print("\n")
        return

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一吨土豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值