用Python设计一个图书借阅管理系统包括查询添加借阅归还图书
时间: 2024-12-22 20:12:42 浏览: 6
Python基于Django图书借阅管理系统源码+数据库(高分毕业设计).zip
4星 · 用户满意度95%
在Python中设计一个简单的图书借阅管理系统,我们可以使用面向对象的方式,创建三个类:`Book`, `User`, 和 `Library`。这里是一个基础的示例:
```python
class Book:
def __init__(self, id, title, available):
self.id = id
self.title = title
self.available = available
class User:
def __init__(self, id, name):
self.id = id
self.name = name
self.borrowed_books = []
def borrow_book(self, book_id):
if book_id in [book.id for book in self.borrowed_books]:
return "这本书已经被你借过"
if book_id not in [book.id for book in Library.books_available]:
return "这本书已经借完了"
borrowed_book = Library.books_available[book_id]
Library.books_available.remove(borrowed_book)
self.borrowed_books.append(borrowed_book)
return f"{self.name}成功借阅了{borrowed_book.title}"
def return_book(self, book_id):
if book_id not in self.borrowed_books:
return "你没有借过这本书"
returned_book = self.borrowed_books.pop(book_id)
Library.books_available.append(returned_book)
return f"{self.name}归还了{returned_book.title}"
class Library:
books_available = {} # 假设图书库存已初始化
@classmethod
def add_book(cls, book_id, title):
new_book = Book(book_id, title, True)
cls.books_available[book_id] = new_book
@classmethod
def query_book(cls, book_id):
if book_id in cls.books_available:
return cls.books_available[book_id]
else:
return "未找到该书"
# 使用示例
Library.add_book(1, "Python入门")
library = Library()
user = User(1, "Alice")
print(user.borrow_book(1)) # Alice成功借阅了Python入门
print(library.query_book(1)) # 查询书籍
user.return_book(1) # Alice归还了Python入门
```
在这个例子中,`add_book` 方法用于添加新书,`query_book` 查找书籍信息,用户通过 `borrow_book` 和 `return_book` 方法操作书籍。注意这只是一个基本框架,实际应用中可能需要更复杂的数据验证、错误处理和数据库交互。
阅读全文