图书管理系统Python 代码
时间: 2024-12-18 19:11:12 浏览: 21
图书管理系统是一个常见的项目,通常用于管理图书馆的书籍信息,包括添加新书、借阅、归还和查询等功能。下面是一个简单的Python图书管理系统的基本框架示例,使用了字典来存储书籍信息:
```python
class Book:
def __init__(self, id, title, author, status="available"):
self.id = id
self.title = title
self.author = author
self.status = status
class LibrarySystem:
def __init__(self):
self.books = {}
# 添加新书
def add_book(self, book_id, title, author):
if book_id not in self.books:
new_book = Book(book_id, title, author)
self.books[book_id] = new_book
print(f"Book added successfully: {title} by {author}")
else:
print("A book with the same ID already exists.")
# 借书
def borrow_book(self, book_id):
if book_id in self.books and self.books[book_id].status == "available":
self.books[book_id].status = "borrowed"
print(f"{book_id} has been borrowed.")
else:
print("Invalid action or book is not available.")
# 归还书
def return_book(self, book_id):
if book_id in self.books and self.books[book_id].status == "borrowed":
self.books[book_id].status = "available"
print(f"{book_id} has been returned.")
else:
print("Invalid action or book is not borrowed.")
# 查询书籍信息
def search_book(self, book_id):
if book_id in self.books:
book = self.books[book_id]
print(f"Title: {book.title}, Author: {book.author}, Status: {book.status}")
else:
print("Book not found.")
# 使用示例
library = LibrarySystem()
library.add_book(1, "Python Crash Course", "Eric Matthes")
library.borrow_book(1)
library.search_book(1)
```
这个例子只是一个基本版本,实际应用中可能会增加用户身份验证、错误处理等复杂功能,并可能采用数据库来持久化数据。
阅读全文