Python入门阶段练习题详解
基于前十天的学习做一个阶段性的练习,后续会每十天做个阶段性的练习、下面是我找了一个需求,大家可以不要看代码从包分析上自己做着练习,并掌握:类、继承、包、异常、open with、方法、属性。
项目需求
-
用户注册:
-
用户可以注册新账户,提供用户名、密码和初始余额。
-
注册信息存储在文件中(如
users.txt
)。 -
用户登录:
-
用户输入用户名和密码登录。
-
登录成功后可以访问购物功能。
-
购物功能:
-
用户可以浏览商品列表。
-
用户可以选择商品加入购物车。
-
用户可以查看购物车并结算。
-
余额与扣款:
-
用户可以查询当前余额。
-
结算时从用户余额中扣除订单金额。
-
如果余额不足,提示用户充值。
-
收货功能:
-
结算成功后,生成订单并提示收货。
-
异常处理:
-
自定义异常处理无效输入、余额不足、商品不存在等情况。
-
继承:
-
使用继承实现用户和商品的基类,扩展出普通用户和VIP用户。
需求分析
包路径及分析
ecommerce/ # 这些都是python package 不是目录
│
├── exceptions/ # 自定义异常(异常练习)
│ └── custom_exceptions.py # LoginError(登录失败异常)BalanceError(余额异常)
│ └── custom_exceptions.py # CartError(购物车异常)ProductError(商品异常)
│
├── models/ # 数据模型 练习类和继承
│ ├── user.py # 类 User字段有 username, password, balance 注册时将信息写入到user.txt
│ ├── user.py # 类 VIPUser 继承 User 字段有 discount(是折扣)
│ └── product.py # 类 Product 字段有 id, name, price 商品信息在product.txt中存储
│ └── product.py # 类 VIPProduct 继承Product 有折扣商品 display_info(显示商品)
│
├── services/ # 业务逻辑
│ ├── auth_service.py # 用户注册和登录 AuthService register() login()
│ ├── cart_service.py # 购物车管理 CartService add_to_cart(添加购物车)view_cart(查看)
│ └── order_service.py # 订单管理 OrderService checkout(扣余额)
│
├── utils/ # 工具类(open with练习)
│ └── file_utils.py # 文件读写工具:read_users(读取用户)write_user(写入用户)
│ # read_products(读取商品)
│
└── main.py # 主程序
# 1. 注册、2. 登录、3. 浏览商品、4. 添加商品到购物车、5. 查看购物车
# 6. 结算、7. 退出
类与方法
model/user
类:
User(基类)方法:
显示用户信息:display_info(self)
初始化:__init__(self, username, password, balance=0)
RegularUser(普通用户)方法:
初始化:__init__(self, username, password, balance=0)
VIPU(vip用户)方法:
初始化:__init__(self, username, password, balance=0, discount=0.7)参数说明discount折扣默认7折。
显示VIP用户信息:display_info(self)
class User:
"""用户基类"""
def __init__(self, username, password, balance=0):
self.username = username
self.password = password
self.balance = balance
def display_info(self):
"""显示用户信息"""
print(f"用户名: {self.username}, 余额: {self.balance}元")
class RegularUser(User):
"""普通用户"""
def __init__(self, username, password, balance=0):
super().__init__(username, password, balance)
class VIPUser(User):
"""VIP用户"""
def __init__(self, username, password, balance=0, discount=0.9):
super().__init__(username, password, balance)
self.discount = discount
def display_info(self):
"""显示VIP用户信息"""
print(f"VIP用户: {self.username}, 余额: {self.balance}元, 折扣: {self.discount}")
model/product
类:
Product(基类)方法:
显示用户信息:display_info(self)
初始化:__init__(self, id, name, price=0)
DiscountedProduct(折扣商品类)方法:
显示用户信息:display_info(self)
初始化:__init__(self, id, name,price, discount=0.7)
class Product:
"""商品基类"""
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
def display_info(self):
"""显示商品信息"""
print(f"商品ID: {self.id}, 名称: {self.name}, 价格: {self.price}元")
class DiscountedProduct(Product):
"""打折商品"""
def __init__(self, id, name, price, discount=0.8):
super().__init__(id, name, price)
self.discount = discount
def display_info(self):
"""显示打折商品信息"""
discounted_price = self.price * self.discount
print(f"打折商品ID: {self.id}, 名称: {self.name}, 原价: {self.price}元, 折后价: {discounted_price}元")
exceptions/custom_exceptions.py
类:
BalanceError(余额相关异常)方法:
初始化:__init__(self, code)
CartError(购物车相关异常)方法:
初始化:__init__(self, code)
ProductError(商品相关异常)方法:
初始化:__init__(self, code)
LoginError(登录相关异常)方法:
初始化:__init__(self, code)
class BalanceError(Exception):
"""余额不足时抛出"""
def __init__(self, code=4000):
self.code = code
if code == 4001:
message = '对不起您的余额不足,请及时充值'
else:
message = '交易异常请稍后重试'
super().__init__(message)
class CartError:
"""购物车相关异常"""
def __init__(self, code=3000):
self.code = code
if code == 3000:
message = '购物车已满'
elif code == 3001:
message = '购物车为空!'
else:
message = '系统异常'
super().__init__(message)
class ProductError:
"""商品相关异常"""
def __init__(self, code=2000):
self.code = code
if code == 2000:
message = '商品不存在'
elif code == 2001:
message = '商品已下架'
elif code == 2002:
message = '商品已售罄'
else:
message = '系统异常'
super().__init__(message)
class LoginError(Exception):
"""登录失败时根据用户名和密码提示"""
def __init__(self, code=1000):
self.code = code
if code == 1000:
message = '用户名不正确,请输入正确用户名'
elif code == 1001:
message = '密码不正确,请输入正确密码'
elif code == 1002:
message = '用户名已存在!'
else:
message = '系统异常'
super().__init__(message)
util/file_utils.py
方法:
read_users():读取全部用户,主要是读取user.txt的用户并返回一个列表
write_user(username,passord,balance):写入到文件user.txt(文件内容:用户名,密码,余额,是否VIP)
read_products():读取全部商品,这个商品无需手动添加这次功能没做,直接添加的3个商品。
import os.path
# Python学习第八天内容文件和os相关操作
def read_users():
"""读取用户信息"""
if os.path.exists("users.txt"):
with open('users.txt', 'r') as file:
list = [line.strip().split(",") for line in file]
# [['python', '123456', '1'], ['python1', '1234561', '2']]
# print(list)
return list
else:
# 没有文件创建文件
with open('users.txt', 'w') as file:
file.write("")
return []
def write_user(username, password, balance):
"""写入用户信息 追加方式"""
with open("users.txt", "a") as file:
file.write(f"{username},{password},{balance}\n")
def read_products():
"""读取商品信息"""
if os.path.exists("products.txt"):
with open("products.txt", "r") as file:
return [line.strip().split(",") for line in file]
else:
# 没有文件创建文件
with open('products.txt', 'w') as file:
file.write("1,商品A,100\n")
file.write("2,商品B,200\n")
file.write("3,商品C,300,0.7\n")
# 后续可以做个添加商品的功能在加个add即可
return [['1','商品A','100'],['2','商品B','200'],['3','商品C','300',0.7]]
# 测试写入用户
# write_user('python','123456',1)
# write_user('python1','1234561',2)
# 测试读入用户
# read_users()
services/auth_service.py
类:
AuthService方法:
注册方法:register(self,username, password, balance, is_vip=False)
登录方法:login(self, username, password)
from ..models.user import RegularUser, VIPUser
from ..exceptions.custom_exceptions import LoginError
from ..util.file_utils import read_users,write_user
class AuthService:
def register(self,username, password, balance, is_vip=False):
"""用户注册"""
users = read_users()
print(username,password,balance,is_vip,read_users)
if len(users)>0 and any(user[0] == username for user in users):
raise LoginError(1002)
if is_vip:
user = VIPUser(username, password, balance)
else:
user = RegularUser(username, password, balance)
write_user(username, password, balance)
print("注册成功!")
def login(self, username, password):
"""用户登录"""
users = read_users()
for user in users:
if user[0] != username:
raise LoginError(1000)
elif user[1] != password:
raise LoginError(1001)
else:
if len(user) > 3 and user[3] == "VIP":
return VIPUser(username, password, float(user[2]))
else:
return RegularUser(username, password, float(user[2]))
raise LoginError(500)
services/cart_service.py
类:
CartService方法:
初始化:__init__(self)初始化一个空的列表
查看购物车:view_cart(self)
添加到购物车:add_to_cart(self, product_id)
from ..models.product import Product, DiscountedProduct
from ..exceptions.custom_exceptions import ProductError,CartError
from ..util.file_utils import read_products
class CartService:
def __init__(self):
self.cart = []
def add_to_cart(self, product_id):
"""添加商品到购物车"""
products = read_products()
for prod in products:
if prod[0] == product_id:
if len(prod) > 3 and prod[3] == "Discounted":
self.cart.append(DiscountedProduct(prod[0], prod[1], float(prod[2])))
else:
self.cart.append(Product(prod[0], prod[1], float(prod[2])))
print(f"已添加商品: {prod[1]}")
return
raise ProductError(2000)
def view_cart(self):
"""查看购物车"""
if not self.cart:
raise CartError(3001)
else:
for product in self.cart:
product.display_info()
services/order_service.py
类:
OrderService方法:
减去余额:checkout(self, user, cart)
from ..exceptions.custom_exceptions import BalanceError
from ..models.user import VIPUser
class OrderService:
def checkout(self, user, cart):
"""结算订单"""
total = sum(product.price for product in cart)
if isinstance(user, VIPUser):
total *= user.discount
if user.balance < total:
raise BalanceError(4001)
user.balance -= total
print(f"结算成功! 订单总金额: {total}元, 当前余额: {user.balance}元")
print("订单已生成,请等待收货!")
main.py
方法:
减去余额:main()函数主入口,启动入口
from day10.ecommerce.exceptions.custom_exceptions import *
from day10.ecommerce.util.file_utils import read_products
from day10.ecommerce.services.auth_sevice import AuthService
from day10.ecommerce.services.cart_service import CartService
from day10.ecommerce.services.order_service import OrderService
def main():
current_user = None
auth_service = AuthService()
cart_service = CartService()
order_service = OrderService()
while True:
print("\n=== 电商系统 ===")
print("1. 注册")
print("2. 登录")
print("3. 浏览商品")
print("4. 添加商品到购物车")
print("5. 查看购物车")
print("6. 结算")
print("7. 退出")
choice = input("请选择操作: ")
if choice == '1':
username = input("请输入用户名: ")
password = input("请输入密码: ")
balance = float(input("请输入初始余额: "))
is_vip = input("是否注册为VIP用户? (y/n): ").lower() == 'y'
try:
auth_service.register(username, password, balance, is_vip)
except LoginError as e:
print(e)
elif choice == '2':
username = input("请输入用户名: ")
password = input("请输入密码: ")
try:
current_user = auth_service.login(username, password)
current_user.display_info()
except LoginError as e:
print(e)
elif choice == '3':
products = read_products()
if len(products) == 0:
print("请先添加商品")
else:
for prod in products:
if len(prod) > 3 and prod[3] == "Discounted":
print(f"打折商品ID: {prod[0]}, 名称: {prod[1]}, 原价: {prod[2]}元")
else:
print(f"商品ID: {prod[0]}, 名称: {prod[1]}, 价格: {prod[2]}元")
elif choice == '4':
if not current_user:
print("请先登录!")
else:
product_id = input("请输入商品ID: ")
try:
cart_service.add_to_cart(product_id)
except ProductError as e:
print(e)
elif choice == '5':
if not current_user:
print("请先登录!")
else:
cart_service.view_cart()
elif choice == '6':
if not current_user:
print("请先登录!")
else:
try:
order_service.checkout(current_user, cart_service.cart)
cart_service.cart = [] # 清空购物车
except BalanceError as e:
print(e)
elif choice == '7':
print("感谢使用,再见!")
break
else:
print("无效选项,请重新选择!")
main()
最后给大家看下我的目录我试过了完美运行,还有就是不用手动新建products.txt和users.txt,因为file中做了兼容判断了。
作者:Leo来编程