Python面向对象编程实战:三个项目完整拆解讲解

简介: 专为零基础设计的Python面向对象编程实战教程,通过学生成绩管理、图书馆管理、综合管理系统三个渐进式项目,详解类、继承、封装、多态等核心概念。每行代码均附详细注释,助你扎实掌握OOP开发能力。(239字)

Python**面向对象编程实战:三个项目完整拆解讲解**

本文专门为零基础学习Python的同学设计,通过三个实际项目,详细讲解Python面向对象编程的核心概念。每个代码段都有详细注释,帮助你理解每一行代码的作用。

目录

项目一:学生成绩管理系统

项目要求:

1. 需求分析

2. 类设计思路

3. 核心方法详解

添加成绩方法

计算平均分方法

重写显示信息方法

4. 主程序逻辑

项目一源代码整合:

项目二:图书馆管理系统

项目要求:

1. 需求分析

2. 类层次结构设计

3. 基类实现

LibraryItem基类

4. 子类实现

Book子类

DVD子类

5. 图书馆管理类

Library类 - 管理所有物品

6. 用户界面设计

项目2完整代码:

项目三:综合管理系统

1. 系统架构设计

2. 扩展学生类

添加借阅管理功能

3. 扩展图书馆物品类

关联借阅者信息

4. 子类:Book和DVD

Book子类

DVD子类

5. 综合管理类

IntegratedSystem类

6. 主程序

主函数

总结

1. 基础概念

2. 面向对象三大特性

3. 项目演进

4. 重要编程技巧

项目三完整源代码


项目一:学生成绩管理系统

项目要求:

定义一个基类Person,包含属性:姓名(name)、年龄(age)。

包含一个方法display_info,用于打印姓名和年龄。

定义一个子类Student,继承自Person,增加属性:

学号(student_id)和一个成绩列表(grades)。包含以下方法:

添加成绩(add_grade):将成绩添加到成绩列表中。

计算平均分(calculate_average):计算并返回成绩列表的平均分。

显示信息(display_info):重写父类的方法,先调用父类的display_info,

然后打印学号和平均分。

创建一个容器students(列表)来存储多个学生对象。

使用循环(for或while)让用户输入多个学生的信息(姓名、年龄、学号)

和至少3门成绩,并将这些学生对象添加到列表中。

遍历学生列表,显示每个学生的信息(包括平均分)。

1. 需求分析

我们需要创建一个系统来管理学生信息和成绩,要求:

  • 存储学生基本信息(姓名、年龄、学号)
  • 管理多门课程成绩
  • 计算平均分
  • 显示完整学生信息

2. 类设计思路

Person**基类**:负责存储人的基本信息

# 定义一个Person类,表示一个人

class Person:

*\#* *初始化方法,创建对象时自动调用*

def \_\_init\_\_(self, name, age):

    *\# self**表示对象本身,name和age是参数*

    self.name = name    *\#* *将参数name赋值给对象的name属性*

    self.age = age      *\#* *将参数age赋值给对象的age属性*

*\#* *显示信息的方法*

def display\_info(self):

    *\#* *打印姓名和年龄*

    print(f"姓名: {self.name}, 年龄: {self.age}")

Student**子类**:继承Person,扩展学生特有功能

# 定义一个Student类,继承自Person类

class Student(Person):

*\#* *初始化方法,需要姓名、年龄和学号*

def \_\_init\_\_(self, name, age, student\_id):

    *\#* *使用super()调用父类Person的初始化方法*

    *\#* *这样父类的name和age属性就会被设置*

    super().\_\_init\_\_(name, age)

    *\#* *设置学生特有的属性*

    self.student\_id = student\_id  *\#* *学号*

    self.grades = \[\]              *\#* *成绩列表,初始为空列表*![](https://ucc.alicdn.com/pic/developer-ecology/vzj76ekdpb3me_a8ed58bec7f64b74b844d1e4d9352b9d.png)

3. 核心方法详解

添加成绩方法

*\#* *添加成绩的方法*

def add\_grade(self, grade):

    *\#* *使用append方法将新成绩添加到成绩列表中*

    self.grades.append(grade)

    *\#* *打印提示信息*

    print(f"已为{self.name}添加成绩: {grade}")

计算平均分方法

*\#* *计算平均分的方法*

def calculate\_average(self):

    *\#* *检查成绩列表是否为空*

    if not self.grades:

        return 0  *\#* *如果为空,返回0*

    *\#* *计算总分:使用sum函数对成绩列表求和*

    *\#* *计算平均分:总分除以成绩数量*

    return sum(self.grades) / len(self.grades)

重写显示信息方法

*\#* *重写显示信息方法(覆盖父类的同名方法)*

def display\_info(self):

    *\#* *先调用父类的display\_info方法,显示姓名和年龄*

    super().display\_info()

    *\#* *计算平均分*

    avg\_grade = self.calculate\_average()

    *\#* *显示学生特有的信息*

    print(f"学号: {self.student\_id}, 平均分: {avg\_grade:.2f}")  *\# :.2f**表示保留两位小数*

    print(f"成绩列表: {self.grades}")

    print("-" \* 40)  *\#* *打印分隔线*

4. 主程序逻辑

# 学生成绩管理系统的主函数

def main_student_system():

students = \[\]  *\#* *创建一个空列表,用于存储所有学生对象*

print("=== 学生成绩管理系统 ===")

*\#* *使用无限循环,直到用户选择退出*

while True:

    print("\\n请输入学生信息:")

    *\#* *获取用户输入*

    name = input("姓名: ")

    age = input("年龄: ")

    student\_id = input("学号: ")

    *\#* *创建学生对象*

    student = Student(name, age, student\_id)

    *\#* *输入至少3门成绩*

    print(f"请为{name}输入至少3门成绩:")

    grade\_count = 0  *\#* *计数器,记录已输入的成绩数量*

    while grade\_count < 3:  *\#* *循环直到输入3门成绩*

        try:

            *\#* *获取成绩输入并转换为浮点数*

            grade = float(input(f"第{grade\_count + 1}门成绩: "))

            *\#* *调用add\_grade方法添加成绩*

            student.add\_grade(grade)

            grade\_count += 1  *\#* *计数器加1*

        except ValueError:

            *\#* *如果输入的不是数字,提示错误*

            print("请输入有效的数字!")

    *\#* *询问是否继续输入更多成绩*

    while True:

        more = input("是否继续输入成绩? (y/n): ").lower()  *\#* *转换为小写*

        if more == 'y':

            try:

                grade = float(input("成绩: "))

                student.add\_grade(grade)

            except ValueError:

                print("请输入有效的数字!")

        elif more == 'n':

            break  *\#* *退出内层循环*

        else:

            print("请输入 y 或 n")  *\#* *输入错误提示*

    *\#* *将学生对象添加到students列表*

    students.append(student)

    print(f"学生 {name} 信息录入完成!")

    *\#* *询问是否继续添加学生*

    continue\_input = input("\\n是否继续添加学生? (y/n): ").lower()

    if continue\_input != 'y':

        break  *\#* *退出外层循环*

*\#* *显示所有学生信息*

print("\\n=== 所有学生信息 ===")

*\#* *遍历students列表中的每个学生对象*

for student in students:

    *\#* *调用每个学生的display\_info方法*

    student.display\_info()

# 如果直接运行这个文件,执行下面的代码

if __name__ == "__main__":

main_student_system() # 调用主函数

项目一源代码整合:

"""

学生成绩管理系统 - 完整版

适合零基础学习Python面向对象编程

"""

class Person:

**"""****人类基类"""**

**def \_\_init\_\_(self, name, age):**

    **#** **初始化姓名和年龄**

    **self.name = name**

    **self.age = age**

**def display\_info(self):**

    **"""****显示基本信息"""**

    **print(f"****姓名: {self.name}, 年龄: {self.age}")**

class Student(Person):

**"""****学生类,继承自Person"""**

**def \_\_init\_\_(self, name, age, student\_id):**

    **#** **调用父类的构造方法**

    **super().\_\_init\_\_(name, age)**

    **#** **学生特有的属性**

    **self.student\_id = student\_id**

    **self.grades = \[\]  #** **成绩列表,初始为空**

**def add\_grade(self, grade):**

    **"""****添加成绩到成绩列表"""**

    **try:**

        **#** **尝试将输入转换为浮点数**

        **grade = float(grade)**

        **self.grades.append(grade)**

        **print(f"****已为 {self.name} 添加成绩: {grade}")**

        **return True**

    **except ValueError:**

        **#** **如果转换失败,提示错误**

        **print(f"****错误: 成绩必须是数字!")**

        **return False**

**def calculate\_average(self):**

    **"""****计算平均分"""**

    **if not self.grades:  #** **如果没有成绩,返回0**

        **return 0**

    **#** **计算平均分:总分 ÷ 成绩数量**

    **return sum(self.grades) / len(self.grades)**

**def display\_info(self):**

    **"""****显示学生完整信息(重写父类方法)"""**

    **#** **先调用父类的显示方法**

    **super().display\_info()**

    **#** **计算平均分**

    **avg\_grade = self.calculate\_average()**

    **#** **显示学生特有信息**

    **print(f"****学号: {self.student\_id}")**

    **print(f"****平均分: {avg\_grade:.2f}")  # 保留两位小数**

    **print(f"****成绩列表: {self.grades}")**

    **print("-" \* 40)  #** **分隔线**

def main_student_system():

**"""****学生成绩管理系统主函数"""**

**students = \[\]  #** **存储所有学生的列表**

**print("===** **学生成绩管理系统 ===")**

**print("****欢迎使用学生成绩管理系统!")**

**#** **主循环:添加学生**

**while True:**

    **print("\\n" + "="\*30)**

    **print("****添加新学生")**

    **#** **获取学生基本信息**

    **name = input("****请输入姓名: ").strip()**

    **if not name:  #** **检查姓名是否为空**

        **print("****姓名不能为空,请重新输入!")**

        **continue**

    **age = input("****请输入年龄: ").strip()**

    **student\_id = input("****请输入学号: ").strip()**

    **#** **创建学生对象**

    **student = Student(name, age, student\_id)**

    **#** **输入成绩**

    **print(f"\\n****正在为 {name} 输入成绩")**

    **print("****请输入至少3门课程的成绩:")**

    **grade\_count = 0  #** **已输入成绩计数**

    **while grade\_count < 3:  #** **至少输入3门成绩**

        **grade = input(f"****第{grade\_count + 1}门课程成绩: ").strip()**

        **if student.add\_grade(grade):**

            **grade\_count += 1  #** **成功添加,计数加1**

    **#** **询问是否继续输入更多成绩**

    **while True:**

        **more\_grades = input("\\n****是否继续输入更多成绩? (y/n): ").strip().lower()**

        **if more\_grades == 'y':**

            **grade = input("****请输入成绩: ").strip()**

            **student.add\_grade(grade)**

        **elif more\_grades == 'n':**

            **break**

        **else:**

            **print("****请输入 y 或 n")**

    **#** **将学生添加到列表**

    **students.append(student)**

    **print(f"\\n****✓** **学生 {name} 信息录入完成!")**

    **#** **询问是否继续添加学生**

    **while True:**

        **continue\_input = input("\\n****是否继续添加学生? (y/n): ").strip().lower()**

        **if continue\_input in \['y', 'n'\]:**

            **break**

        **else:**

            **print("****请输入 y 或 n")**

    **if continue\_input != 'y':**

        **break**

**#** **显示所有学生信息**

**print("\\n" + "="\*50)**

**print("****所有学生信息汇总:")**

**print("="\*50)**

**if not students:**

    **print("****没有学生信息!")**

**else:**

    **for i, student in enumerate(students, 1):**

        **print(f"\\n****学生 {i}:")**

        **student.display\_info()**

# 程序入口

if __name__ == "__main__":

**try:**

    **main\_student\_system()**

**except KeyboardInterrupt:**

    **print("\\n\\n****程序被用户中断")**

**except Exception as e:**

    **print(f"\\n****程序发生错误: {e}")**

**finally:**

    **print("\\n****感谢使用学生成绩管理系统!")**

项目二:图书馆管理系统

项目要求:

定义一个基类LibraryItem(图书馆物品),包含属性:标题(title)、作者(author)、是否可借(is_available)。包含方法:

借出(borrow):如果可借,则将is_available设置为False,并打印借出成功;否则打印已借出。

归还(return_item):将is_available设置为True,并打印归还成功。

显示信息(display_info):打印标题、作者和借出状态。

定义两个子类Book和DVD,继承自LibraryItem。

Book类增加属性:出版社(publisher)和页数(pages)。

DVD类增加属性:导演(director)和时长(duration)。

分别重写display_info方法,在基类的基础上增加显示各自的特殊属性。

定义一个类Library,用于管理多个LibraryItem对象。包含属性:一个物品列表(容器)。包含方法:

添加物品(add_item):将物品添加到列表中。

借出物品(borrow_item):根据标题查找物品,如果找到且可借,则借出;否则提示不可借。

归还物品(return_item):根据标题查找物品,如果找到且已借出,则归还;否则提示错误。

显示所有物品(display_all_items):显示图书馆中所有物品的信息。

创建一个Library实例,添加若干本书和DVD。然后使用一个循环,模拟用户操作:可以借出物品、归还物品、查看所有物品。用户可以选择退出。

1. 需求分析

构建一个图书馆管理系统,要求:

  • 管理不同类型的图书资料(图书、DVD)
  • 实现借出和归还功能
  • 显示详细的资料信息
  • 提供用户交互界面

2. 类层次结构设计

LibraryItem (基类)

├── Book (子类)

└── DVD (子类)

3. 基类实现

LibraryItem**基类**

# 图书馆物品基类

class LibraryItem:

*\#* *初始化方法*

def \_\_init\_\_(self, title, author):

    self.title = title          *\#* *物品标题*

    self.author = author        *\#* *作者/导演*

    self.is\_available = True    *\#* *是否可借,初始值为True(可借)*

*\#* *借出方法*

def borrow(self):

    *\#* *检查物品是否可借*

    if self.is\_available:

        *\#* *如果可借,设置为不可借*

        self.is\_available = False

        print(f"'{self.title}' 借出成功!")

        return True  *\#* *返回成功*

    else:

        *\#* *如果不可借,提示信息*

        print(f"'{self.title}' 已被借出,暂时不可借。")

        return False  *\#* *返回失败*

*\#* *归还方法*

def return\_item(self):

    *\#* *设置为可借状态*

    self.is\_available = True

    print(f"'{self.title}' 归还成功!")

*\#* *显示基本信息方法*

def display\_info(self):

    *\#* *根据is\_available的值显示不同的状态*

    status = "可借" if self.is\_available else "已借出"

    print(f"标题: {self.title}")

    print(f"作者/导演: {self.author}")

    print(f"状态: {status}")

4. 子类实现

Book**子类**

# 图书类,继承自LibraryItem

class Book(LibraryItem):

*\#* *初始化方法*

def \_\_init\_\_(self, title, author, publisher, pages):

    *\#* *调用父类的初始化方法*

    super().\_\_init\_\_(title, author)

    *\#* *添加图书特有的属性*

    self.publisher = publisher  *\#* *出版社*

    self.pages = pages          *\#* *页数*

*\#* *重写显示信息方法*

def display\_info(self):

    *\#* *先调用父类的显示方法*

    super().display\_info()

    *\#* *添加图书特有的信息*

    print(f"出版社: {self.publisher}")

    print(f"页数: {self.pages}页")

    print("-" \* 30)  *\#* *打印分隔线*

DVD**子类**

# DVD**类,继承自LibraryItem

class DVD(LibraryItem):

*\#* *初始化方法*

def \_\_init\_\_(self, title, director, duration):

    *\#* *对于DVD,author参数实际上是director*

    super().\_\_init\_\_(title, director)

    self.director = director    *\#* *导演*

    self.duration = duration    *\#* *时长(分钟)*

*\#* *重写显示信息方法*

def display\_info(self):

    *\#* *先调用父类的显示方法*

    super().display\_info()

    *\#* *添加DVD特有的信息*

    print(f"导演: {self.director}")

    print(f"时长: {self.duration}分钟")

    print("-" \* 30)  *\#* *打印分隔线*

5. 图书馆管理类

Library**类 - 管理所有物品**

# 图书馆管理类

class Library:

*\#* *初始化方法*

def \_\_init\_\_(self):

    self.items = \[\]  *\#* *创建一个空列表,用于存储所有图书馆物品*

*\#* *添加物品方法*

def add\_item(self, item):

    *\#* *将物品添加到列表中*

    self.items.append(item)

    print(f"已添加: {item.title}")

*\#* *借出物品方法*

def borrow\_item(self, title):

    *\#* *遍历所有物品*

    for item in self.items:

        *\#* *比较标题(不区分大小写)*

        if item.title.lower() == title.lower():

            *\#* *如果找到匹配的物品,尝试借出*

            if item.is\_available:

                item.borrow()  *\#* *调用物品的借出方法*

                return True    *\#* *返回成功*

            else:

                print(f"'{title}' 已被借出!")

                return False   *\#* *返回失败*

    *\#* *如果循环结束都没找到,提示未找到*

    print(f"未找到标题为 '{title}' 的物品!")

    return False

*\#* *归还物品方法*

def return\_item(self, title):

    *\#* *遍历所有物品*

    for item in self.items:

        *\#* *比较标题(不区分大小写)*

        if item.title.lower() == title.lower():

            *\#* *如果找到匹配的物品,检查是否已借出*

            if not item.is\_available:

                item.return\_item()  *\#* *调用物品的归还方法*

                return True         *\#* *返回成功*

            else:

                print(f"'{title}' 未被借出,无需归还!")

                return False        *\#* *返回失败*

    *\#* *如果循环结束都没找到,提示未找到*

    print(f"未找到标题为 '{title}' 的物品!")

    return False

*\#* *显示所有物品方法*

def display\_all\_items(self):

    *\#* *检查物品列表是否为空*

    if not self.items:

        print("图书馆目前没有任何物品!")

        return

    print("\\n=== 图书馆所有物品 ===")

    *\#* *使用enumerate遍历,同时获取索引和物品*

    for i, item in enumerate(self.items, 1):  *\#* *从1开始计数*

        print(f"物品 {i}:")

        item.display\_info()  *\#* *调用物品的显示信息方法*

6. 用户界面设计

# 图书馆管理系统主函数

def main_library_system():

*\#* *创建图书馆实例*

library = Library()

*\#* *添加一些初始物品*

print("正在初始化图书馆物品...")

library.add\_item(Book("Python编程入门", "张三", "清华大学出版社", 300))

library.add\_item(Book("数据结构与算法", "李四", "人民邮电出版社", 450))

library.add\_item(DVD("肖申克的救赎", "弗兰克·德拉邦特", 142))

library.add\_item(DVD("阿甘正传", "罗伯特·泽米吉斯", 142))

print("=== 欢迎使用图书馆管理系统 ===")

*\#* *主循环*

while True:

    print("\\n请选择操作:")

    print("1. 借出物品")

    print("2. 归还物品")

    print("3. 查看所有物品")

    print("4. 添加新物品")

    print("5. 退出系统")

    *\#* *获取用户选择*

    choice = input("请输入选择 (1-5): ").strip()  *\# strip()**去除首尾空格*

    if choice == "1":

        *\#* *借出物品*

        title = input("请输入要借出的物品标题: ").strip()

        library.borrow\_item(title)

    elif choice == "2":

        *\#* *归还物品*

        title = input("请输入要归还的物品标题: ").strip()

        library.return\_item(title)

    elif choice == "3":

        *\#* *查看所有物品*

        library.display\_all\_items()

    elif choice == "4":

        *\#* *添加新物品*

        print("\\n选择要添加的物品类型:")

        print("1. 图书")

        print("2. DVD")

        item\_type = input("请选择 (1-2): ").strip()

        if item\_type == "1":

            *\#* *添加图书*

            title = input("图书标题: ")

            author = input("作者: ")

            publisher = input("出版社: ")

            pages = input("页数: ")

            try:

                *\#* *尝试将页数转换为整数*

                book = Book(title, author, publisher, int(pages))

                library.add\_item(book)

            except ValueError:

                *\#* *如果转换失败,提示错误*

                print("页数必须是数字!")

        elif item\_type == "2":

            *\#* *添加DVD*

            title = input("DVD标题: ")

            director = input("导演: ")

            duration = input("时长(分钟): ")

            try:

                *\#* *尝试将时长转换为整数*

                dvd = DVD(title, director, int(duration))

                library.add\_item(dvd)

            except ValueError:

                *\#* *如果转换失败,提示错误*

                print("时长必须是数字!")

        else:

            print("无效选择!")

    elif choice == "5":

        *\#* *退出系统*

        print("感谢使用图书馆管理系统,再见!")

        break  *\#* *退出循环*

    else:

        print("无效选择,请重新输入!")

# 运行图书馆系统

if __name__ == "__main__":

main\_library\_system()

项目2完整代码:

"""

图书馆管理系统 - 完整版

管理图书和DVD的借阅和归还

"""

class LibraryItem:

"""图书馆物品基类"""

def \_\_init\_\_(self, title, author):

    # 基本属性

    self.title = title

    self.author = author

    self.is\_available = True  # 是否可借,初始为可借

def borrow(self):

    """借出物品"""

    if self.is\_available:

        self.is\_available = False  # 设置为已借出

        print(f"✓ '{self.title}' 借出成功!")

        return True

    else:

        print(f"✗ '{self.title}' 已被借出,暂时不可借。")

        return False

def return\_item(self):

    """归还物品"""

    self.is\_available = True  # 设置为可借

    print(f"✓ '{self.title}' 归还成功!")

def display\_info(self):

    """显示物品基本信息"""

    # 根据状态显示不同的文字

    status = "可借" if self.is\_available else "已借出"

    print(f"标题: {self.title}")

    print(f"作者/导演: {self.author}")

    print(f"状态: {status}")

class Book(LibraryItem):

"""图书类,继承自LibraryItem"""

def \_\_init\_\_(self, title, author, publisher, pages):

    # 调用父类构造方法

    super().\_\_init\_\_(title, author)

    # 图书特有属性

    self.publisher = publisher  # 出版社

    self.pages = pages          # 页数

def display\_info(self):

    """显示图书详细信息(重写父类方法)"""

    # 先显示基本信息

    super().display\_info()

    # 显示图书特有信息

    print(f"出版社: {self.publisher}")

    print(f"页数: {self.pages}页")

    print("-" \* 30)  # 分隔线

class DVD(LibraryItem):

"""DVD类,继承自LibraryItem"""

def \_\_init\_\_(self, title, director, duration):

    # 调用父类构造方法

    super().\_\_init\_\_(title, director)

    # DVD特有属性

    self.director = director    # 导演

    self.duration = duration    # 时长(分钟)

def display\_info(self):

    """显示DVD详细信息(重写父类方法)"""

    # 先显示基本信息

    super().display\_info()

    # 显示DVD特有信息

    print(f"导演: {self.director}")

    print(f"时长: {self.duration}分钟")

    print("-" \* 30)  # 分隔线

class Library:

"""图书馆管理类"""

def \_\_init\_\_(self):

    self.items = \[\]  # 存储所有物品的列表

def add\_item(self, item):

    """添加物品到图书馆"""

    self.items.append(item)

    print(f"✓ 已添加: {item.title}")

def borrow\_item(self, title):

    """根据标题借出物品"""

    # 遍历所有物品

    for item in self.items:

        # 比较标题(不区分大小写)

        if item.title.lower() == title.lower():

            # 尝试借出

            return item.borrow()

    # 如果没找到

    print(f"✗ 未找到标题为 '{title}' 的物品!")

    return False

def return\_item(self, title):

    """根据标题归还物品"""

    # 遍历所有物品

    for item in self.items:

        # 比较标题(不区分大小写)

        if item.title.lower() == title.lower():

            if not item.is\_available:  # 检查是否已借出

                item.return\_item()

                return True

            else:

                print(f"✗ '{title}' 未被借出,无需归还!")

                return False

    # 如果没找到

    print(f"✗ 未找到标题为 '{title}' 的物品!")

    return False

def display\_all\_items(self):

    """显示图书馆所有物品"""

    if not self.items:  # 检查列表是否为空

        print("图书馆目前没有任何物品!")

        return

    print("\\n=== 图书馆所有物品 ===")

    # 遍历并显示所有物品

    for i, item in enumerate(self.items, 1):

        print(f"物品 {i}:")

        item.display\_info()

def search\_item(self, keyword):

    """根据关键词搜索物品"""

    found\_items = \[\]

    # 遍历所有物品

    for item in self.items:

        # 在标题和作者中搜索

        if (keyword.lower() in item.title.lower() or

            keyword.lower() in item.author.lower()):

            found\_items.append(item)

    # 显示搜索结果

    if found\_items:

        print(f"\\n找到 {len(found\_items)} 个匹配 '{keyword}' 的物品:")

        for i, item in enumerate(found\_items, 1):

            print(f"结果 {i}:")

            item.display\_info()

    else:

        print(f"\\n没有找到匹配 '{keyword}' 的物品")

    return found\_items

def main_library_system():

"""图书馆管理系统主函数"""

# 创建图书馆实例

library = Library()

# 添加初始物品

print("正在初始化图书馆物品...")

initial\_items = \[

    Book("Python编程从入门到实践", "Eric Matthes", "人民邮电出版社", 459),

    Book("流畅的Python", "Luciano Ramalho", "人民邮电出版社", 628),

    Book("数据结构与算法分析", "Mark Allen Weiss", "机械工业出版社", 391),

    DVD("肖申克的救赎", "Frank Darabont", 142),

    DVD("阿甘正传", "Robert Zemeckis", 142),

    DVD("星际穿越", "Christopher Nolan", 169)

\]

for item in initial\_items:

    library.add\_item(item)

print("\\n" + "="\*50)

print("=== 欢迎使用图书馆管理系统 ===")

# 主菜单循环

while True:

    print("\\n请选择操作:")

    print("1. 借出物品")

    print("2. 归还物品")

    print("3. 查看所有物品")

    print("4. 搜索物品")

    print("5. 添加新物品")

    print("6. 退出系统")

    choice = input("请输入选择 (1-6): ").strip()

    if choice == "1":

        # 借出物品

        title = input("请输入要借出的物品标题: ").strip()

        if title:  # 检查输入是否为空

            library.borrow\_item(title)

        else:

            print("标题不能为空!")

    elif choice == "2":

        # 归还物品

        title = input("请输入要归还的物品标题: ").strip()

        if title:  # 检查输入是否为空

            library.return\_item(title)

        else:

            print("标题不能为空!")

    elif choice == "3":

        # 查看所有物品

        library.display\_all\_items()

    elif choice == "4":

        # 搜索物品

        keyword = input("请输入搜索关键词: ").strip()

        if keyword:  # 检查输入是否为空

            library.search\_item(keyword)

        else:

            print("搜索关键词不能为空!")

    elif choice == "5":

        # 添加新物品

        print("\\n选择要添加的物品类型:")

        print("1. 图书")

        print("2. DVD")

        item\_type = input("请选择 (1-2): ").strip()

        if item\_type == "1":

            # 添加图书

            print("\\n请输入图书信息:")

            title = input("标题: ").strip()

            author = input("作者: ").strip()

            publisher = input("出版社: ").strip()

            pages = input("页数: ").strip()

            if title and author and publisher and pages:

                try:

                    book = Book(title, author, publisher, int(pages))

                    library.add\_item(book)

                except ValueError:

                    print("错误: 页数必须是数字!")

            else:

                print("错误: 所有字段都不能为空!")

        elif item\_type == "2":

            # 添加DVD

            print("\\n请输入DVD信息:")

            title = input("标题: ").strip()

            director = input("导演: ").strip()

            duration = input("时长(分钟): ").strip()

            if title and director and duration:

                try:

                    dvd = DVD(title, director, int(duration))

                    library.add\_item(dvd)

                except ValueError:

                    print("错误: 时长必须是数字!")

            else:

                print("错误: 所有字段都不能为空!")

        else:

            print("无效选择!")

    elif choice == "6":

        # 退出系统

        print("感谢使用图书馆管理系统,再见!")

        break

    else:

        print("无效选择,请重新输入!")

# 程序入口

if __name__ == "__main__":

try:

    main\_library\_system()

except KeyboardInterrupt:

    print("\\n\\n程序被用户中断")

except Exception as e:

    print(f"\\n程序发生错误: {e}")

finally:

    print("程序结束")

项目三:综合管理系统

1. 系统架构设计

这个项目将学生系统和图书馆系统结合起来,实现更复杂的功能:

  • 学生可以借阅图书馆物品
  • 记录借阅时间和到期时间
  • 限制最大借阅数量
  • 统一管理界面

首先需要导入时间相关的模块:

# 导入日期时间模块,用于处理时间和日期

from datetime import datetime, timedelta

2. 扩展学生类

添加借阅管理功能

python

# 学生类,继承自Person类

class Student(Person):

*\#* *初始化方法*

def \_\_init\_\_(self, name, age, student\_id):

    *\#* *调用父类的初始化方法*

    super().\_\_init\_\_(name, age)

    *\#* *设置学生特有属性*

    self.student\_id = student\_id  *\#* *学号*

    self.grades = \[\]              *\#* *成绩列表*

    self.borrowed\_items = \[\]      *\#* *借阅记录列表,初始为空*

*\#* *添加成绩方法(带验证)*

def add\_grade(self, grade):

    *\#* *检查成绩是否在合理范围内(0-100分)*

    if 0 <= grade <= 100:

        self.grades.append(grade)  *\#* *添加成绩*

        return True  *\#* *返回成功*

    else:

        return False  *\#* *返回失败*

*\#* *计算平均分方法*

def calculate\_average(self):

    *\#* *检查成绩列表是否为空*

    if not self.grades:

        return 0  *\#* *如果为空,返回0*

    *\#* *计算平均分:总分 ÷ 成绩数量*

    return sum(self.grades) / len(self.grades)

*\#* *借阅物品方法*

def borrow\_item(self, item):

    *\#* *检查是否已达到最大借阅数量(3个)*

    if len(self.borrowed\_items) < 3:

        *\#* *创建借阅记录字典*

        record = {

            'item': item,  *\#* *借阅的物品对象*

            'borrow\_date': datetime.now(),  *\#* *借阅时间(当前时间)*

            'due\_date': datetime.now() + timedelta(days=30)  *\#* *应还时间(30天后)*

        }

        *\#* *将借阅记录添加到列表中*

        self.borrowed\_items.append(record)

        return True  *\#* *借阅成功*

    else:

        return False  *\#* *借阅失败(已达上限)*

*\#* *重写显示信息方法*

def display\_info(self):

    *\#* *先调用父类的显示方法*

    super().display\_info()

    *\#* *计算平均分*

    avg\_grade = self.calculate\_average()

    *\#* *显示学生特有信息*

    print(f"学号: {self.student\_id}")

    print(f"平均分: {avg\_grade:.2f}")

    print(f"借阅物品数量: {len(self.borrowed\_items)}")

    *\#* *如果有借阅记录,显示详细信息*

    if self.borrowed\_items:

        print("借阅记录:")

        *\#* *遍历所有借阅记录,enumerate用于同时获取索引和记录*

        for i, record in enumerate(self.borrowed\_items, 1):  *\#* *从1开始计数*

            *\#* *计算剩余天数*

            due\_days = (record\['due\_date'\] - datetime.now()).days

            *\#* *显示借阅信息*

            print(f"  {i}. {record\['item'\].title} (剩余{due\_days}天)")

    *\#* *打印分隔线*

    print("-" \* 40)

3. 扩展图书馆物品类

关联借阅者信息

python

# 图书馆物品基类

class LibraryItem:

*\#* *初始化方法*

def \_\_init\_\_(self, title, author):

    self.title = title          *\#* *物品标题*

    self.author = author        *\#* *作者/导演*

    self.is\_available = True    *\#* *是否可借*

    self.borrower = None        *\#* *当前借阅者,初始为None(无人借阅)*

*\#* *借出方法(带学生参数)*

def borrow(self, student):

    *\#* *检查物品是否可借且学生借阅成功*

    if self.is\_available and student.borrow\_item(self):

        *\#* *设置物品为不可借状态*

        self.is\_available = False

        *\#* *记录借阅者*

        self.borrower = student

        return True  *\#* *借阅成功*

    return False  *\#* *借阅失败*

*\#* *归还方法*

def return\_item(self):

    *\#* *设置物品为可借状态*

    self.is\_available = True

    *\#* *清除借阅者记录*

    self.borrower = None

*\#* *显示信息方法*

def display\_info(self):

    *\#* *根据状态显示不同的信息*

    if self.is\_available:

        status = "可借"

    else:

        *\#* *如果已借出,显示借阅者姓名*

        status = f"已借出给: {self.borrower.name}"

    print(f"标题: {self.title}")

    print(f"作者/导演: {self.author}")

    print(f"状态: {status}")

4. 子类:Book和DVD

Book**子类**

python

# 图书类,继承自LibraryItem

class Book(LibraryItem):

*\#* *初始化方法*

def \_\_init\_\_(self, title, author, publisher, pages, isbn):

    *\#* *调用父类初始化方法*

    super().\_\_init\_\_(title, author)

    *\#* *设置图书特有属性*

    self.publisher = publisher  *\#* *出版社*

    self.pages = pages          *\#* *页数*

    self.isbn = isbn            *\# ISBN**号(图书的唯一标识)*

*\#* *重写显示信息方法*

def display\_info(self):

    *\#* *先调用父类的显示方法*

    super().display\_info()

    *\#* *添加图书特有信息*

    print(f"出版社: {self.publisher}")

    print(f"页数: {self.pages}")

    print(f"ISBN: {self.isbn}")

    print("-" \* 30)  *\#* *分隔线*

DVD**子类**

python

# DVD**类,继承自LibraryItem

class DVD(LibraryItem):

*\#* *初始化方法*

def \_\_init\_\_(self, title, director, duration, category):

    *\#* *调用父类初始化方法*

    super().\_\_init\_\_(title, director)

    *\#* *设置DVD特有属性*

    self.director = director    *\#* *导演*

    self.duration = duration    *\#* *时长(分钟)*

    self.category = category    *\#* *分类(如:科幻、动作等)*

*\#* *重写显示信息方法*

def display\_info(self):

    *\#* *先调用父类的显示方法*

    super().display\_info()

    *\#* *添加DVD特有信息*

    print(f"导演: {self.director}")

    print(f"时长: {self.duration}分钟")

    print(f"分类: {self.category}")

    print("-" \* 30)  *\#* *分隔线*

5. 综合管理类

IntegratedSystem**类**

python

# 综合管理系统类

class IntegratedSystem:

*\#* *初始化方法*

def \_\_init\_\_(self):

    self.students = \[\]        *\#* *存储所有学生的列表*

    self.library\_items = \[\]   *\#* *存储所有图书馆物品的列表*

*\#* *添加学生方法*

def add\_student(self, student):

    self.students.append(student)  *\#* *将学生添加到列表*

*\#* *添加图书馆物品方法*

def add\_library\_item(self, item):

    self.library\_items.append(item)  *\#* *将物品添加到列表*

*\#* *根据学号查找学生*

def find\_student(self, student\_id):

    *\#* *遍历所有学生*

    for student in self.students:

        *\#* *比较学号*

        if student.student\_id == student\_id:

            return student  *\#* *找到学生,返回学生对象*

    return None  *\#* *没找到,返回None*

*\#* *根据标题查找物品*

def find\_item(self, title):

    *\#* *遍历所有物品*

    for item in self.library\_items:

        *\#* *比较标题(不区分大小写)*

        if item.title.lower() == title.lower():

            return item  *\#* *找到物品,返回物品对象*

    return None  *\#* *没找到,返回None*

*\#* *学生借阅物品方法*

def borrow\_item\_to\_student(self, student\_id, item\_title):

    *\# 1.* *查找学生*

    student = self.find\_student(student\_id)

    *\# 2.* *查找物品*

    item = self.find\_item(item\_title)

    *\#* *检查学生是否存在*

    if not student:

        print("学生不存在!")

        return False

    *\#* *检查物品是否存在*

    if not item:

        print("物品不存在!")

        return False

    *\# 3.* *执行借阅操作*

    if item.borrow(student):

        print(f"{student.name} 成功借阅 {item.title}")

        return True  *\#* *借阅成功*

    else:

        print("借阅失败!可能已达借阅上限或物品不可借。")

        return False  *\#* *借阅失败*

*\#* *显示所有信息方法*

def display\_all\_info(self):

    *\#* *显示学生信息*

    print("\\n=== 学生信息 ===")

    *\#* *遍历所有学生*

    for student in self.students:

        student.display\_info()  *\#* *调用学生的显示方法*

    *\#* *显示图书馆物品信息*

    print("\\n=== 图书馆物品 ===")

    *\#* *遍历所有物品*

    for item in self.library\_items:

        item.display\_info()  *\#* *调用物品的显示方法*

6. 主程序

主函数

python

# 综合管理系统主函数

def main_integrated_system():

*\#* *创建综合系统实例*

system = IntegratedSystem()

*\#* *初始化数据*

print("初始化系统数据...")

*\#* *添加学生1*

student1 = Student("张三", 20, "2023001")

student1.add\_grade(85)  *\#* *添加成绩*

student1.add\_grade(92)

student1.add\_grade(78)

*\#* *添加学生2*

student2 = Student("李四", 21, "2023002")

student2.add\_grade(90)

student2.add\_grade(88)

student2.add\_grade(95)

*\#* *将学生添加到系统*

system.add\_student(student1)

system.add\_student(student2)

*\#* *添加图书馆物品*

book1 = Book("Python编程", "王五", "清华大学出版社", 350, "978-7-123-45678-9")

book2 = Book("数据结构", "赵六", "人民邮电出版社", 280, "978-7-987-65432-1")

dvd1 = DVD("星际穿越", "克里斯托弗·诺兰", 169, "科幻")

*\#* *将物品添加到系统*

system.add\_library\_item(book1)

system.add\_library\_item(book2)

system.add\_library\_item(dvd1)

print("=== 综合管理系统 ===")

*\#* *主循环*

while True:

    print("\\n请选择操作:")

    print("1. 学生借阅")

    print("2. 查看所有信息")

    print("3. 添加新学生")

    print("4. 添加新物品")

    print("5. 退出")

    *\#* *获取用户选择*

    choice = input("请选择 (1-5): ")

    if choice == "1":

        *\#* *学生借阅功能*

        student\_id = input("请输入学号: ")

        item\_title = input("请输入物品标题: ")

        system.borrow\_item\_to\_student(student\_id, item\_title)

    elif choice == "2":

        *\#* *查看所有信息*

        system.display\_all\_info()

    elif choice == "3":

        *\#* *添加新学生*

        name = input("学生姓名: ")

        age = input("年龄: ")

        student\_id = input("学号: ")

        *\#* *创建学生对象*

        student = Student(name, age, student\_id)

        print("请输入至少3门成绩:")

        *\#* *循环输入3门成绩*

        for i in range(3):

            while True:  *\#* *无限循环,直到输入有效成绩*

                try:

                    *\#* *获取成绩输入*

                    grade = float(input(f"第{i+1}门成绩: "))

                    *\#* *尝试添加成绩*

                    if student.add\_grade(grade):

                        break  *\#* *添加成功,退出内层循环*

                    else:

                        print("成绩必须在0-100之间!")

                except ValueError:

                    *\#* *如果输入的不是数字,提示错误*

                    print("请输入数字!")

        *\#* *将学生添加到系统*

        system.add\_student(student)

        print("学生添加成功!")

    elif choice == "4":

        *\#* *添加新物品*

        print("选择物品类型: 1.图书 2.DVD")

        item\_type = input("请选择: ")

        if item\_type == "1":

            *\#* *添加图书*

            title = input("标题: ")

            author = input("作者: ")

            publisher = input("出版社: ")

            pages = input("页数: ")

            isbn = input("ISBN: ")

            try:

                *\#* *创建图书对象*

                book = Book(title, author, publisher, int(pages), isbn)

                *\#* *添加到系统*

                system.add\_library\_item(book)

                print("图书添加成功!")

            except ValueError:

                *\#* *如果页数不是数字,提示错误*

                print("页数必须是数字!")

        elif item\_type == "2":

            *\#* *添加DVD*

            title = input("标题: ")

            director = input("导演: ")

            duration = input("时长: ")

            category = input("分类: ")

            try:

                *\#* *创建DVD对象*

                dvd = DVD(title, director, int(duration), category)

                *\#* *添加到系统*

                system.add\_library\_item(dvd)

                print("DVD添加成功!")

            except ValueError:

                *\#* *如果时长不是数字,提示错误*

                print("时长必须是数字!")

        else:

            print("无效选择!")

    elif choice == "5":

        *\#* *退出系统*

        print("再见!")

        break  *\#* *退出循环*

    else:

        print("无效选择!")

# 如果直接运行这个文件,执行主函数

if __name__ == "__main__":

main_integrated_system()

总结

通过这三个项目,我们学习了:

1. 基础概念

  • 类:对象的蓝图,定义了对象的属性和方法
  • 对象:类的实例,具有类定义的属性和方法
  • 属性:对象的数据(如姓名、年龄)
  • 方法:对象的行为(如显示信息、添加成绩)

2. 面向对象三大特性

  • 封装:将数据和方法包装在类中
  • 继承:子类可以继承父类的属性和方法
  • 多态:不同对象对同一方法有不同的实现

3. 项目演进

  • 项目一:基础的学生管理系统
  • 项目二:增加了图书馆管理系统
  • 项目三:将两个系统结合,实现更复杂的功能

4. 重要编程技巧

  • 使用super()调用父类方法
  • 使用try-except处理可能的错误
  • 使用循环和条件语句控制程序流程
  • 使用列表存储多个对象

项目三完整源代码

"""

综合管理系统 - 完整版

结合学生管理和图书馆管理功能

"""

# 导入日期时间模块

from datetime import datetime, timedelta

class Person:

"""人类基类"""

def \_\_init\_\_(self, name, age):

    self.name = name

    self.age = age

def display\_info(self):

    """显示基本信息"""

    print(f"姓名: {self.name}, 年龄: {self.age}")

class Student(Person):

"""学生类"""

def \_\_init\_\_(self, name, age, student\_id):

    # 调用父类构造方法

    super().\_\_init\_\_(name, age)

    # 学生特有属性

    self.student\_id = student\_id

    self.grades = \[\]              # 成绩列表

    self.borrowed\_items = \[\]      # 借阅记录列表

def add\_grade(self, grade):

    """添加成绩(带验证)"""

    try:

        grade = float(grade)

        if 0 <= grade <= 100:  # 验证成绩范围

            self.grades.append(grade)

            return True

        else:

            print("成绩必须在0-100之间!")

            return False

    except ValueError:

        print("成绩必须是数字!")

        return False

def calculate\_average(self):

    """计算平均分"""

    if not self.grades:

        return 0

    return sum(self.grades) / len(self.grades)

def borrow\_item(self, item):

    """借阅物品"""

    # 检查借阅数量限制(最多3个)

    if len(self.borrowed\_items) < 3:

        # 创建借阅记录

        record = {

            'item': item,

            'borrow\_date': datetime.now(),

            'due\_date': datetime.now() + timedelta(days=30)  # 30天后到期

        }

        self.borrowed\_items.append(record)

        return True

    else:

        print(f"{self.name} 已达到最大借阅数量(3个)!")

        return False

def return\_item(self, item\_title):

    """归还物品"""

    for record in self.borrowed\_items:

        if record\['item'\].title.lower() == item\_title.lower():

            self.borrowed\_items.remove(record)

            print(f"{self.name} 已归还 {item\_title}")

            return True

    print(f"{self.name} 没有借阅 {item\_title}")

    return False

def display\_info(self):

    """显示学生完整信息"""

    # 显示基本信息

    super().display\_info()

    avg\_grade = self.calculate\_average()

    # 显示学生特有信息

    print(f"学号: {self.student\_id}")

    print(f"平均分: {avg\_grade:.2f}")

    print(f"成绩列表: {self.grades}")

    print(f"借阅物品数量: {len(self.borrowed\_items)}")

    # 显示借阅记录

    if self.borrowed\_items:

        print("借阅记录:")

        for i, record in enumerate(self.borrowed\_items, 1):

            due\_days = (record\['due\_date'\] - datetime.now()).days

            status = "已过期" if due\_days < 0 else f"剩余{due\_days}天"

            print(f"  {i}. {record\['item'\].title} ({status})")

    print("-" \* 50)

class LibraryItem:

"""图书馆物品基类"""

def \_\_init\_\_(self, title, author):

    self.title = title

    self.author = author

    self.is\_available = True

    self.borrower = None  # 当前借阅者

def borrow(self, student):

    """借出给指定学生"""

    if self.is\_available:

        if student.borrow\_item(self):

            self.is\_available = False

            self.borrower = student

            return True

    return False

def return\_item(self):

    """归还物品"""

    if self.borrower:

        self.borrower.return\_item(self.title)

    self.is\_available = True

    self.borrower = None

def display\_info(self):

    """显示物品信息"""

    if self.is\_available:

        status = "可借"

    else:

        status = f"已借出给: {self.borrower.name}"

    print(f"标题: {self.title}")

    print(f"作者/导演: {self.author}")

    print(f"状态: {status}")

class Book(LibraryItem):

"""图书类"""

def \_\_init\_\_(self, title, author, publisher, pages, isbn=""):

    super().\_\_init\_\_(title, author)

    self.publisher = publisher

    self.pages = pages

    self.isbn = isbn

def display\_info(self):

    """显示图书详细信息"""

    super().display\_info()

    print(f"出版社: {self.publisher}")

    print(f"页数: {self.pages}")

    if self.isbn:

        print(f"ISBN: {self.isbn}")

    print("-" \* 30)

class DVD(LibraryItem):

"""DVD类"""

def \_\_init\_\_(self, title, director, duration, category):

    super().\_\_init\_\_(title, director)

    self.director = director

    self.duration = duration

    self.category = category

def display\_info(self):

    """显示DVD详细信息"""

    super().display\_info()

    print(f"导演: {self.director}")

    print(f"时长: {self.duration}分钟")

    print(f"分类: {self.category}")

    print("-" \* 30)

class IntegratedSystem:

"""综合管理系统"""

def \_\_init\_\_(self):

    self.students = \[\]

    self.library\_items = \[\]

def add\_student(self, student):

    """添加学生"""

    self.students.append(student)

    print(f"✓ 已添加学生: {student.name}")

def add\_library\_item(self, item):

    """添加图书馆物品"""

    self.library\_items.append(item)

    print(f"✓ 已添加物品: {item.title}")

def find\_student(self, student\_id):

    """根据学号查找学生"""

    for student in self.students:

        if student.student\_id == student\_id:

            return student

    return None

def find\_item(self, title):

    """根据标题查找物品"""

    for item in self.library\_items:

        if item.title.lower() == title.lower():

            return item

    return None

def borrow\_item\_to\_student(self, student\_id, item\_title):

    """学生借阅物品"""

    student = self.find\_student(student\_id)

    if not student:

        print(f"✗ 找不到学号为 {student\_id} 的学生")

        return False

    item = self.find\_item(item\_title)

    if not item:

        print(f"✗ 找不到标题为 {item\_title} 的物品")

        return False

    if item.borrow(student):

        print(f"✓ {student.name} 成功借阅 {item.title}")

        return True

    else:

        print(f"✗ 借阅失败")

        return False

def return\_item\_from\_student(self, student\_id, item\_title):

    """学生归还物品"""

    student = self.find\_student(student\_id)

    if not student:

        print(f"✗ 找不到学号为 {student\_id} 的学生")

        return False

    item = self.find\_item(item\_title)

    if not item:

        print(f"✗ 找不到标题为 {item\_title} 的物品")

        return False

    if student.return\_item(item\_title):

        item.return\_item()

        return True

    return False

def display\_all\_info(self):

    """显示所有信息"""

    print("\\n" + "="\*60)

    print("系统信息汇总")

    print("="\*60)

    # 显示学生信息

    print(f"\\n学生信息 (共{len(self.students)}人):")

    if self.students:

        for student in self.students:

            student.display\_info()

    else:

        print("暂无学生信息")

    # 显示图书馆物品信息

    print(f"\\n图书馆物品 (共{len(self.library\_items)}件):")

    if self.library\_items:

        for item in self.library\_items:

            item.display\_info()

    else:

        print("暂无图书馆物品")

def get\_overdue\_items(self):

    """获取过期未还的物品"""

    overdue\_items = \[\]

    for student in self.students:

        for record in student.borrowed\_items:

            due\_days = (record\['due\_date'\] - datetime.now()).days

            if due\_days < 0:  # 已过期

                overdue\_items.append({

                    'student': student,

                    'item': record\['item'\],

                    'overdue\_days': -due\_days

                })

    return overdue\_items

def main_integrated_system():

"""综合管理系统主函数"""

# 创建系统实例

system = IntegratedSystem()

# 初始化数据

print("正在初始化系统数据...")

# 添加示例学生

student1 = Student("张三", 20, "2023001")

student1.add\_grade(85)

student1.add\_grade(92)

student1.add\_grade(78)

student2 = Student("李四", 21, "2023002")

student2.add\_grade(90)

student2.add\_grade(88)

student2.add\_grade(95)

student3 = Student("王五", 19, "2023003")

student3.add\_grade(76)

student3.add\_grade(85)

student3.add\_grade(92)

system.add\_student(student1)

system.add\_student(student2)

system.add\_student(student3)

# 添加示例图书馆物品

book1 = Book("Python编程从入门到实践", "Eric Matthes", "人民邮电出版社", 459, "9787115428028")

book2 = Book("流畅的Python", "Luciano Ramalho", "人民邮电出版社", 628, "9787115454157")

book3 = Book("数据结构与算法", "陈越", "高等教育出版社", 328, "9787040398331")

dvd1 = DVD("肖申克的救赎", "Frank Darabont", 142, "剧情")

dvd2 = DVD("星际穿越", "Christopher Nolan", 169, "科幻")

dvd3 = DVD("疯狂动物城", "Byron Howard", 108, "动画")

system.add\_library\_item(book1)

system.add\_library\_item(book2)

system.add\_library\_item(book3)

system.add\_library\_item(dvd1)

system.add\_library\_item(dvd2)

system.add\_library\_item(dvd3)

print("\\n" + "="\*50)

print("=== 综合管理系统 ===")

print("="\*50)

# 主菜单循环

while True:

    print("\\n请选择操作:")

    print("1. 学生借阅")

    print("2. 学生归还")

    print("3. 查看所有信息")

    print("4. 添加新学生")

    print("5. 添加新物品")

    print("6. 查看过期借阅")

    print("7. 退出系统")

    choice = input("请选择 (1-7): ").strip()

    if choice == "1":

        # 学生借阅

        print("\\n--- 学生借阅 ---")

        student\_id = input("请输入学号: ").strip()

        item\_title = input("请输入物品标题: ").strip()

        if student\_id and item\_title:

            system.borrow\_item\_to\_student(student\_id, item\_title)

        else:

            print("学号和物品标题都不能为空!")

    elif choice == "2":

        # 学生归还

        print("\\n--- 学生归还 ---")

        student\_id = input("请输入学号: ").strip()

        item\_title = input("请输入物品标题: ").strip()

        if student\_id and item\_title:

            system.return\_item\_from\_student(student\_id, item\_title)

        else:

            print("学号和物品标题都不能为空!")

    elif choice == "3":

        # 查看所有信息

        system.display\_all\_info()

    elif choice == "4":

        # 添加新学生

        print("\\n--- 添加新学生 ---")

        name = input("姓名: ").strip()

        age = input("年龄: ").strip()

        student\_id = input("学号: ").strip()

        if name and age and student\_id:

            student = Student(name, age, student\_id)

            # 输入成绩

            print(f"\\n请为 {name} 输入至少3门成绩:")

            grade\_count = 0

            while grade\_count < 3:

                grade = input(f"第{grade\_count + 1}门成绩: ").strip()

                if student.add\_grade(grade):

                    grade\_count += 1

            system.add\_student(student)

        else:

            print("所有字段都不能为空!")

    elif choice == "5":

        # 添加新物品

        print("\\n--- 添加新物品 ---")

        print("选择物品类型: 1.图书 2.DVD")

        item\_type = input("请选择 (1-2): ").strip()

        if item\_type == "1":

            # 添加图书

            title = input("标题: ").strip()

            author = input("作者: ").strip()

            publisher = input("出版社: ").strip()

            pages = input("页数: ").strip()

            isbn = input("ISBN (可选): ").strip()

            if title and author and publisher and pages:

                try:

                    book = Book(title, author, publisher, int(pages), isbn)

                    system.add\_library\_item(book)

                except ValueError:

                    print("错误: 页数必须是数字!")

            else:

                print("错误: 标题、作者、出版社、页数不能为空!")

        elif item\_type == "2":

            # 添加DVD

            title = input("标题: ").strip()

            director = input("导演: ").strip()

            duration = input("时长(分钟): ").strip()

            category = input("分类: ").strip()

            if title and director and duration and category:

                try:

                    dvd = DVD(title, director, int(duration), category)

                    system.add\_library\_item(dvd)

                except ValueError:

                    print("错误: 时长必须是数字!")

            else:

                print("错误: 所有字段都不能为空!")

        else:

            print("无效选择!")

    elif choice == "6":

        # 查看过期借阅

        print("\\n--- 过期借阅记录 ---")

        overdue\_items = system.get\_overdue\_items()

        if overdue\_items:

            print(f"找到 {len(overdue\_items)} 个过期借阅:")

            for i, record in enumerate(overdue\_items, 1):

                print(f"{i}. {record\['student'\].name} 借阅的 '{record\['item'\].title}'")

                print(f"   已过期 {record\['overdue\_days'\]} 天")

        else:

            print("没有过期借阅记录")

    elif choice == "7":

        # 退出系统

        print("感谢使用综合管理系统,再见!")

        break

    else:

        print("无效选择,请重新输入!")

# 程序入口

if __name__ == "__main__":

try:

    main\_integrated\_system()

except KeyboardInterrupt:

    print("\\n\\n程序被用户中断")

except Exception as e:

    print(f"\\n程序发生错误: {e}")

finally:

    print("程序结束")
相关文章
|
21天前
|
人工智能 JSON API
全网刷屏的 Jev 模型正式开放!一手实战测评 + 保姆级教程
全网爆火的 Jev 模型是什么?有什么用?怎么使用?怎么接入 AI 编程工具?效果真的好么?傻子可懂的 Jev 保姆级实战教程 + 项目实战测评来啦
9057 28
|
20天前
|
人工智能 并行计算 PyTorch
秋叶 ComfyUI 2026 整合包 v3.2 完整部署教程:Python 3.13 + Torch 2.13 全栈升级
秋叶aaaki ComfyUI 2026年8月整合包v3.2正式发布!全面升级Python 3.13.11、PyTorch 2.13.0+cu130及ComfyUI v0.30.2,原生支持MiniMax H3、Wan 2.2、Qwen-Image-2.1等2026主流音视频/图像模型,解压即用,无需环境配置。
4098 16
|
19天前
|
人工智能 测试技术 API
最近全网爆火的 Jev 到底是什么?适合干什么、怎么用,一篇讲透!
Jev是TypeSafe AI推出的“系统一模型”,不生成文本,专做毫秒级结构化决策:Choice(多选)、Score(打分)、Noul(是非概率)。响应快193倍、成本低444倍,适合工单路由、内容审核、测试定级等高频判断场景。
2329 4
最近全网爆火的 Jev 到底是什么?适合干什么、怎么用,一篇讲透!
|
7天前
|
存储 人工智能 并行计算
大模型本地部署终端选型方法论:以 Qwen3.8-27B 为例的四档分层完整流程
本文提出一套大模型本地部署终端选型方法论:定约束、定档位、定框架、定参数四步决策法,配合入门、主力、质量、无损四档分层模型。以 Qwen3.8-27B 实测数据为例,逐环节解读显存、带宽、存储、散热、系统、预算等要素,给出面向不同预算的优选方案、决策自查清单与市场观察框架。文末前瞻 AI 笔记本的 CPU+GPU 与统一内存两条路线,论证四步决策法在新品类上的延续性。
|
6天前
|
人工智能 JSON 自然语言处理
2026 年 Jev 决策模型深度拆解:原理解读、实战测评与保姆级落地教程
有一款特殊AI模型在开发者圈子刷屏,它摒弃传统大模型擅长的对话聊天能力,专注做高速结构化决策,它就是TypeSafe AI推出的Jev模型。该模型由ChatGPT共同发明人Diogo Almeida主导研发,定位为**System One Model(系统一模型)**,对标人类大脑快速直觉判断的思维模式,在响应延迟、调用成本、结构化输出稳定性上相比传统生成式大模型有着巨大差异。本文会完整拆解Jev底层原理、三大核心原语能力、适用业务场景,同时提供可直接运行的curl、Python代码示例,并且结合多组实测数据,客观分析模型优势与能力边界,帮助普通开发者和AI应用从业者快速上手落地。
488 1
|
14天前
|
人工智能 Linux 开发者
【2026国内使用】Codex安装过程一篇讲透(Win/Mac/Linux全支持)
Codex是OpenAI推出的AI编程智能体,可读取本地项目、理解需求并自动修改代码。支持桌面GUI、命令行(CLI)及VS Code/Cursor插件三种形态,覆盖可视化操作、终端高效开发与编辑器无缝集成场景,助开发者用自然语言驱动编码全流程。(239字)
1069 2
【2026国内使用】Codex安装过程一篇讲透(Win/Mac/Linux全支持)
|
8天前
|
人工智能 Linux Windows
千问办公(QwenWork)官网入口:其实有2个,一个是网页端千问办公,一个是介绍指南页面
千问办公(QwenWork)是阿里云推出的AI智能办公平台,支持网页端直接使用及Windows/Mac/Linux客户端下载。提供PPT生成、财报分析、网页搭建等AI功能,个人版免费,企业版198元/席/月。详情见官网qwenwork.cn或阿里云产品页。
1041 0
千问办公(QwenWork)官网入口:其实有2个,一个是网页端千问办公,一个是介绍指南页面