Python 程序示例:图书管理系统,实现读者借书和还书功能

本程序使用 Python 语言编写,模拟图书管理系统的借书和还书功能。程序中定义了 BookReader 两个类,分别表示图书和读者,并实现了借书、还书和列出借书情况等功能。

代码示例:

class Book:
    def __init__(self, title, number, author, publisher):
        self.title = title
        self.number = number
        self.author = author
        self.publisher = publisher

class Reader:
    def __init__(self, name, id):
        self.name = name
        self.id = id
        self.books = []

    def borrow_book(self, book):
        if len(self.books) >= 6:
            print('You have borrowed the maximum number of books.')
        else:
            self.books.append(book)
            print('You have borrowed the book', book.title)

    def return_book(self, book):
        if book in self.books:
            self.books.remove(book)
            print('You have returned the book', book.title)
        else:
            print('You have not borrowed the book', book.title)

    def list_borrowed_books(self):
        print('Borrowed books:')
        for book in self.books:
            print(book.title)

# 创建几本图书
book1 = Book('Python Programming', 123456, 'John Smith', 'O'Reilly Media')
book2 = Book('Data Structures and Algorithms', 789012, 'Alice Johnson', 'Addison-Wesley Professional')
book3 = Book('Artificial Intelligence', 345678, 'Bob Brown', 'MIT Press')

# 创建一个读者
reader1 = Reader('Tom', 1001)

# 借几本书
reader1.borrow_book(book1)
reader1.borrow_book(book2)
reader1.borrow_book(book3)

# 显示借的书
reader1.list_borrowed_books()

# 还书
reader1.return_book(book2)

# 再次显示借的书
reader1.list_borrowed_books()

代码解释:

  1. 定义 Book 类:

    • __init__ 方法用于初始化图书对象,包含书名、编号、作者和出版社等属性。
  2. 定义 Reader 类:

    • __init__ 方法用于初始化读者对象,包含姓名、ID 和借书列表等属性。
    • borrow_book 方法用于借书,最多可以借 6 本书。
    • return_book 方法用于还书。
    • list_borrowed_books 方法用于列出借书情况。
  3. 创建图书和读者对象:

    • 创建了 book1book2book3 三个图书对象。
    • 创建了 reader1 一个读者对象。
  4. 借书、还书和显示借书情况:

    • reader1 借了 book1book2book3 三本书。
    • reader1 还了 book2 这本书。
    • 最后显示了 reader1 借书情况。

输出结果:

You have borrowed the book Python Programming
You have borrowed the book Data Structures and Algorithms
You have borrowed the book Artificial Intelligence
Borrowed books:
Python Programming
Data Structures and Algorithms
Artificial Intelligence
You have returned the book Data Structures and Algorithms
Borrowed books:
Python Programming
Artificial Intelligence

总结:

本程序展示了如何使用 Python 语言实现一个简单的图书管理系统,并演示了类、对象、方法等面向对象编程的概念。您可以根据自己的需要扩展和改进本程序,使其更加完善。

Python 程序示例:图书管理系统,实现读者借书和还书功能

原文地址: https://www.cveoy.top/t/topic/oakX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录