写一个图书管理系统的代码
时间: 2023-11-30 07:06:03 浏览: 72
图书管理系统的代码
好的,这里给你一个简单的图书管理系统的代码,使用 Python 语言编写,主要功能包括添加图书、借阅图书、归还图书和查询图书:
```python
class Book:
def __init__(self, book_id, title, author, status):
self.book_id = book_id
self.title = title
self.author = author
self.status = status
class Library:
def __init__(self):
self.books = []
# 添加图书
def add_book(self, book_id, title, author):
book = Book(book_id, title, author, "available")
self.books.append(book)
print("图书添加成功!")
# 借阅图书
def borrow_book(self, book_id):
for book in self.books:
if book.book_id == book_id:
if book.status == "available":
book.status = "borrowed"
print("借阅成功!")
return
else:
print("该图书已被借出!")
return
print("找不到该图书!")
# 归还图书
def return_book(self, book_id):
for book in self.books:
if book.book_id == book_id:
if book.status == "borrowed":
book.status = "available"
print("归还成功!")
return
else:
print("该图书已在库中!")
return
print("找不到该图书!")
# 查询图书
def search_book(self, query):
result = []
for book in self.books:
if query.lower() in book.title.lower() or query.lower() in book.author.lower():
result.append(book)
if len(result) == 0:
print("未找到相关图书!")
else:
for book in result:
print(f"书名:{book.title},作者:{book.author},状态:{book.status}")
```
你可以通过实例化 `Library` 类来创建一个图书馆对象,然后调用相应的方法来管理图书:
```python
library = Library()
# 添加图书
library.add_book("001", "Python从入门到精通", "张三")
library.add_book("002", "Java从入门到精通", "李四")
# 借阅图书
library.borrow_book("001")
library.borrow_book("001") # 该图书已被借出!
# 归还图书
library.return_book("001")
# 查询图书
library.search_book("python")
```
希望能帮到你!
阅读全文