利用Python实现图书馆管理系统代码
时间: 2024-12-27 09:27:17 浏览: 5
在Python中实现一个简单的图书馆管理系统可以包含借阅、归还图书以及查询库存等基本功能。这里提供一个简化的示例代码框架:
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
self.is_borrowed = False
class Library:
def __init__(self):
self.books = {}
def add_book(self, book_id, title, author):
self.books[book_id] = Book(title, author)
def borrow_book(self, book_id, borrower_name):
if book_id not in self.books or self.books[book_id].is_borrowed:
print("这本书已借出或不存在")
else:
self.books[book_id].is_borrowed = True
print(f"{borrower_name}成功借走了{self.books[book_id].title}")
def return_book(self, book_id):
if book_id not in self.books or not self.books[book_id].is_borrowed:
print("这本书未被借出或不存在")
else:
self.books[book_id].is_borrowed = False
print(f"{book_id}已被归还")
def search_books(self, keyword):
results = [book for book in self.books.values() if keyword in book.title]
if results:
print("搜索结果:")
for result in results:
print(result.title)
else:
print("找不到匹配的书籍")
# 使用示例
library = Library()
library.add_book(1, "Python编程", "John Doe")
library.borrow_book(1, "Alice")
library.search_books("Doe")
library.return_book(1)
```
这个例子只是一个基础版本,实际应用中可能需要连接数据库存储书籍信息,添加用户认证机制,并处理并发控制等问题。
阅读全文