帮我写一个图书管理系统的完整代码
时间: 2023-08-20 16:58:19 浏览: 83
当然可以帮你写一个图书管理系统的代码。以下是一个简单的示例,包含了基本的图书管理功能,包括添加图书、借阅图书、归还图书和查询图书等操作。
```python
class Book:
def __init__(self, title, author, available=True):
self.title = title
self.author = author
self.available = available
def __str__(self):
return f"{self.title} by {self.author}"
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def borrow_book(self, title):
for book in self.books:
if book.title == title and book.available:
book.available = False
return f"You have borrowed '{book}'."
return "Book not available for borrowing."
def return_book(self, title):
for book in self.books:
if book.title == title and not book.available:
book.available = True
return f"You have returned '{book}'."
return "Invalid book or already returned."
def search_book(self, title):
for book in self.books:
if book.title == title:
return f"'{book}' is available." if book.available else f"'{book}' is currently borrowed."
return "Book not found in the library."
# 示例用法
library = Library()
book1 = Book("Python Crash Course", "Eric Matthes")
book2 = Book("Clean Code", "Robert C. Martin")
book3 = Book("The Pragmatic Programmer", "Andrew Hunt, David Thomas")
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
print(library.search_book("Clean Code")) # 输出: 'Clean Code by Robert C. Martin' is available.
print(library.borrow_book("Clean Code")) # 输出: You have borrowed 'Clean Code by Robert C. Martin'.
print(library.search_book("Clean Code")) # 输出: 'Clean Code by Robert C. Martin' is currently borrowed.
print(library.return_book("Clean Code")) # 输出: You have returned 'Clean Code by Robert C. Martin'.
print(library.search_book("Clean Code")) # 输出: 'Clean Code by Robert C. Martin' is available.
```
这只是一个简单的示例,你可以根据实际需求进行扩展和修改。希望对你有帮助!
阅读全文