引言
在编程学习过程中,构建项目是一个非常有效的方式,不仅能巩固和应用所学的知识,还能通过实践来解决实际问题。本文将通过几个经典的项目示例来展示如何用面向对象的方式设计和实现一个完整的系统,包括学生成绩管理系统、图书馆管理系统、电子商务网站模拟以及猜数字游戏。通过这些项目,你将能够掌握如何运用面向对象设计原则来处理数据存储、异常处理、系统功能模块化等常见问题,从而为更复杂的应用程序开发打下坚实的基础。
学生成绩管理系统
下面是学生管理系统的简单功能,其余几个类似,这里不做一一展示
这个学生成绩管理系统实现了以下功能:
添加学生信息
录入学生成绩
查询单个学生的成绩信息
查看某科目的班级平均分
数据持久化(保存到CSV文件)
系统的特点:
使用面向对象设计,将学生和管理系统分别封装
实现了异常处理,确保输入数据的正确性
使用CSV文件进行数据存储
提供了友好的命令行界面
首先创建主要的类和文件结构:
python
class Student:
def __init__(self, student_id, name):
self.student_id = student_id
self.name = name
self.scores = {} # 科目: 分数
def add_score(self, subject, score):
self.scores[subject] = score
def get_average(self):
if not self.scores:
return 0
return sum(self.scores.values()) / len(self.scores)
python
import csv
import os
class StudentManager:
def __init__(self):
self.students = {} # student_id: Student对象
self.file_path = "ts.csv"
self.load_data()
def add_student(self, student):
self.students[student.student_id] = student
def get_student(self, student_id):
return self.students.get(student_id)
def add_score(self, student_id, subject, score):
if student_id in self.students:
self.students[student_id].add_score(subject, score)
def get_class_average(self, subject):
scores = [s.scores.get(subject, 0) for s in self.students.values()
if subject in s.scores]
if not scores:
return 0
return sum(scores) / len(scores)
def save_to_csv(self):
with open(self.file_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['学号', '姓名', '科目', '分数'])
for student in self.students.values():
for subject, score in student.scores.items():
writer.writerow([student.student_id, student.name,
subject, score])
def load_data(self):
if not os.path.exists(self.file_path):
return
with open(self.file_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
next(reader) # 跳过表头
for row in reader:
student_id, name, subject, score = row
if student_id not in self.students:
self.students[student_id] = Student(student_id, name)
self.students[student_id].add_score(subject, float(score))
python
# -*- coding: utf-8 -*-
rom student import Student
rom student_manager import StudentManager
def main():
manager = StudentManager()
while True:
print("\n=== 学生成绩管理系统 ===")
print("1. 添加学生")
print("2. 录入成绩")
print("3. 查询学生成绩")
print("4. 查看班级平均分")
print("5. 保存并退出")
choice = input("请选择操作 (1-5): ").strip()
if choice == '1':
student_id = input("请输入学号: ").strip()
name = input("请输入姓名: ").strip()
student = Student(student_id, name)
manager.add_student(student)
print("学生添加成功!")
elif choice == '2':
student_id = input("请输入学号: ").strip()
subject = input("请输入科目: ").strip()
try:
score = float(input("请输入分数: ").strip())
manager.add_score(student_id, subject, score)
print("成绩录入成功!")
except ValueError:
print("分数输入错误!请输入有效的数字。")
elif choice == '3':
student_id = input("请输入要查询的学号: ").strip()
student = manager.get_student(student_id)
if student:
print(f"\n学号:{student.student_id}")
print(f"姓名:{student.name}")
print("成绩:")
for subject, score in student.scores.items():
print(f"{subject}: {score}")
print(f"平均分:{student.get_average():.2f}")
else:
print("未找到该学生!")
elif choice == '4':
subject = input("请输入要查询的科目: ").strip()
avg = manager.get_class_average(subject)
print(f"{subject}的班级平均分是:{avg:.2f}")
elif choice == '5':
manager.save_to_csv()
print("数据已保存,程序退出!")
break
else:
print("无效的选择,请重试!")
if __name__ == "__main__":
main()
界面如下
图书馆管理系统
python
class Book:
def __init__(self, book_id, title,author):
self.book_id = book_id
self.title = title
self.author = author
self.is_borrowed = False
self.borrow_history = [] # 借阅历史记录
def borrow(self, user_id, borrow_date):
if not self.is_borrowed:
self.is_borrowed = True
self.borrow_history.append({
'user_id': user_id,
'borrow_date': borrow_date,
'return_date': None
})
return True
return False
def return_book(self, return_date):
if self.is_borrowed:
self.is_borrowed = False
self.borrow_history[-1]['return_date'] = return_date
return True
return False
python
class User:
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
self.borrowed_books = [] # 当前借阅的图书ID列表
def borrow_book(self, book_id):
self.borrowed_books.append(book_id)
def return_book(self, book_id):
if book_id in self.borrowed_books:
self.borrowed_books.remove(book_id)
return True
return False
python
import json
import datetime
from book import Book
from user import User
class Library:
def __init__(self):
self.books = {} # book_id: Book对象
self.users = {} # user_id: User对象
self.load_data()
def add_book(self, book):
self.books[book.book_id] =
def add_user(self, user):
self.users[user.user_id] = user
def borrow_book(self, user_id, book_id):
if user_id not in self.users or book_id not in self.books:
return False
book = self.books[book_id]
user = self.users[user_id]
if book.borrow(user_id, datetime.datetime.now()):
user.borrow_book(book_id)
return True
return False
def return_book(self, user_id, book_id):
if user_id not in self.users or book_id not in self.books:
return False
book = self.books[book_id]
user = self.users[user_id]
if book.return_book(datetime.datetime.now()):
user.return_book(book_id)
return True
return False
def save_data(self):
data = {
'books': {
bid: {
'title': book.title,
'author': book.author,
'is_borrowed': book.is_borrowed,
'borrow_history': book.borrow_history
} for bid, book in self.books.items()
},
'users': {
uid: {
'name': user.name,
'borrowed_books': user.borrowed_books
} for uid, user in self.users.items()
}
}
with open('library_data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, default=str)
def load_data(self):
try:
with open('library_data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
for book_id, book_data in data['books'].items():
book = Book(book_id, book_data['title'], book_data['author'])
book.is_borrowed = book_data['is_borrowed']
book.borrow_history = book_data['borrow_history']
self.books[book_id] = book
for user_id, user_data in data['users'].items():
user = User(user_id, user_data['name'])
user.borrowed_books = user_data['borrowed_books']
self.users[user_id] = user
except FileNotFoundError:
pass
界面如下
电子商务网站模拟
python
class Product:
def __init__(self, product_id, name, price, stock):
self.product_id = product_id
self.name = name
self.price = price
self.stock = stock
def decrease_stock(self, quantity):
if self.stock >= quantity:
self.stock -= quantity
return True
return False
python
class ShoppingCart:
def __init__(self):
self.items = {} # product_id: quantity
def add_item(self, product_id, quantity):
if product_id in self.items:
self.items[product_id] += quantity
else:
self.items[product_id] = quantity
def remove_item(self, product_id):
if product_id in self.items:
del self.items[product_id]
def update_quantity(self, product_id, quantity):
if quantity <= 0:
self.remove_item(product_id)
else:
self.items[product_id] = quantity
def get_total(self, products):
total = 0
for product_id, quantity in self.items.items():
if product_id in products:
total += products[product_id].price * quantity
return total
python
import datetime
class Order:
def __init__(self, order_id, user_id, items, total_amount):
self.order_id = order_id
self.user_id = user_id
self.items = items # {product_id: quantity}
self.total_amount = total_amount
self.order_date = datetime.datetime.now()
self.status = "pending" # pending, paid, delivered
def pay(self):
self.status = "paid"
def ship(self):
self.status = "shipped"
def deliver(self):
self.status = "delivered"
python
import json
from product import Product
from cart import ShoppingCart
from order import Order
class Store:
def __init__(self):
self.products = {} # product_id: Product对象
self.orders = {} # order_id: Order对象
self.load_data()
def add_product(self, product):
self.products[product.product_id] = product
def create_order(self, user_id, cart):
order_id = str(len(self.orders) + 1)
total = cart.get_total(self.products)
# 检查库存
for product_id, quantity in cart.items.items():
if not self.products[product_id].decrease_stock(quantity):
return None
order = Order(order_id, user_id, cart.items.copy(), total)
self.orders[order_id] = order
return order
def save_data(self):
data = {
'products': {
pid: {
'name': p.name,
'price': p.price,
'stock': p.stock
} for pid, p in self.products.items()
},
'orders': {
oid: {
'user_id': o.o.items,
'total_amount': o.total_amount,
'order_date': str(o.order_date),
'status': o.status
} for oid, o in self.orders.items()
}
}
with open('store_data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
def load_data(self):
try:
with open('store_data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
for pid, p_data in data['products'].items():
self.products[pid] = Product(
pid, p_data['name'], p_data['price'], p_data['stock']
)
for oid, o_data in data['orders'].items():
self.orders[oid] = Order(
oid, o_data['user_id'], o_data['items'],
o_data['total_amount']
)
self.orders[oid].status = o_data['status']
except FileNotFoundError:
pass
python
from store import Store
from product import Product
from cart import ShoppingCart
def main():
store = Store()
cart = ShoppingCart() while True:
print("\n电子商务系统")
print("1. 添加商品")
print("2. 查看商品列表")
print("3. 添加到购物车")
print("4. 查看购物车")
print("5. 修改购物车")
print("6. 创建订单")
print("7. 查看订单")
print("8. 保存并退出")
choice = input("请选择操作 (1-8): ")
if choice == '1':
product_id = input("请输入商品ID: ")
name = input("请输入商品名称: ")
try:
price = float(input("请输入价格: "))
stock = int(input("请输入库存数量: "))
product = Product(product_id, name, price, stock)
store.add_product(product)
print("商品添加成功!")
except ValueError:
print("输入错误!")
elif choice == '2':
print("\n商品列表:")
for pid, product in store.products.items():
print(f"ID: {pid}")
print(f"名称: {product.name}")
print(f"价格: ¥{product.price:.2f}")
print(f"库存: {product.stock}")
print()
elif choice == '3':
product_id = input("请输入商品ID: ")
if product_id in store.products:
try:
quantity = int(input("请输入数量: "))
if quantity > 0:
cart.add_item(product_id, quantity)
print("添加成功!")
else:
print("数量必须大于0!")
except ValueError:
print("输入错误!")
else:
print("商品不存在!")
elif choice == '4':
print("\n购物车:")
total = 0
for pid, quantity in cart.items.items():
if pid in store.products:
product = store.products[pid]
subtotal = product.price * quantity
total += subtotal
print(f"商品: {product.name}")
print(f"数量: {quantity}")
print(f"小计: ¥{subtotal:.2f}")
print()
print(f"总计: ¥{total:.2f}")
elif choice == '5':
product_id = input("请输入要修改的商品ID: ")
if product_id in cart.items:
try:
quantity = int(input("请输入新的数量(0表示删除): "))
cart.update_quantity(product_id, quantity)
print("修改成功!")
except ValueError:
print("输入错误!")
else:
print("购物车中没有该商品!")
elif choice == '6':
if not cart.items:
print("购物车为空!")
continue
user_id = input("请输入用户ID: ")
order = store.create_order(user_id, cart)
if order:
print(f"订单创建成功!订单号:{order.order_id}")
cart = ShoppingCart() # 清空购物车
else:
print("订单创建失败!库存不足")
elif choice == '7':
print("\n订单列表:")
for oid, order in store.orders.items():
print(f"订单号: {oid}")
print(f"用户ID: {order.user_id}")
print(f"总金额: ¥{order.total_amount:.2f}")
print(f"状态: {order.status}")
print("商品:")
for pid, quantity in order.items.items():
if pid in store.products:
print(f"- {store.products[pid].name} x {quantity}")
print()
elif choice == '8':
store.save_data()
print("数据已保存,程序退出!")
break
else:
print("无效的选择,请重试!")
if __name__ == "__main__":
main()
界面如下
猜数字游戏
python
import random
import json
from datetime import datetime
class NumberGame:
def __init__(self):
self.target = 0
self.max_tries = 10
self.high_scores = []
self.load_scores()
def start_new_game(self):
self.target = random.randint(1, 100)
return self.target
def check_guess(self, guess):
if guess < self.target:
return "太低了"
elif guess > self.target:
return "太高了"
else:
return "猜对了"
def add_score(self, player_name, tries):
score = {
'player': player_name,
'tries': tries,
'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
self.high_scores.append(score)
self.high_scores.sort(key=lambda x: x['tries'])
self.high_scores = self.high_scores[:10] # 只保留前10名
self.save_scores()
def save_scores(self):
with open('high_scores.json', 'w', encoding='utf-8') as f:
json.dump(self.high_scores, f, ensure_ascii=False)
def load_scores(self):
try:
with open('high_scores.json', 'r', encoding='utf-8') as f:
self.high_scores = json.load(f)
except FileNotFoundError:
self.high_scores = []
python
from game import NumberGame
def main():
game = NumberGame()
while True:
print("\n猜数字游戏")
print("1. 开始新游戏")
print("2. 查看排行榜")
print("3. 退出")
choice = input("请选择操作 (1-3): ")
if choice == '1':
game.start_new_game()
tries = 0
print(f"\n游戏开始!你有{game.max_tries}次机会猜一个1-100之间的数。")
while tries < game.max_tries:ry:
guess = int(input(f"还剩{game.max_tries - tries}次机会,请猜一个数: "))
tries += 1
if guess < 1 or guess > 100:
print("请猜1-100之间的数!")
continue
result = game.check_guess(guess)
print(result)
if result == "猜对了":
print(f"恭喜你用了{tries}次猜对了!")
name = input("请输入你的名字记录成绩: ")
game.add_score(name, tries)
break
except ValueError:
print("请输入有效的数字!")
if tries >= game.max_tries:
print(f"游戏结束!正确答案是{game.target}")
elif choice == '2':
print("\n排行榜:")
for i, score in enumerate(game.high_scores, 1):
print(f"{i}. {score['player']}: {score['tries']}次 ({score['date']})")
elif choice == '3':
print("谢谢游戏,再见!")
break
else:
print("无效的选择,请重试!")
if __name__ == "__main__":
main()
界面如下
结语
本文展示的几个项目涵盖了日常生活中常见的管理和游戏系统,旨在帮助读者更好地理解如何运用Python进行面向对象的编程实践。每个项目都涉及到不同的功能模块与实际问题,通过这些示例,你可以学到如何设计易于维护的代码结构,如何处理用户输入、数据存储以及程序的整体逻辑。无论你是初学者还是有一定基础的开发者,这些项目都能为你提供一定的编程经验和思维方式,帮助你在未来的编程道路上更加自信地面对挑战。希望你能从这些项目中获得启发,并将所学应用到更多实际的编程任务中!
提供Python期末大作业指导,欢迎资讯