帮我用Python写一个图书管理系统代码
时间: 2023-08-28 18:37:00 浏览: 60
好的,以下是一个简单的图书管理系统的Python代码:
```python
class Book:
def __init__(self, title, author, ISBN, available=True):
self.title = title
self.author = author
self.ISBN = ISBN
self.available = available
class Library:
def __init__(self):
self.books = []
def add_book(self, title, author, ISBN, available=True):
book = Book(title, author, ISBN, available)
self.books.append(book)
def remove_book(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
def find_book(self, title):
for book in self.books:
if book.title == title:
return book
return None
def list_books(self):
for book in self.books:
print(book.title)
def borrow_book(self, title):
book = self.find_book(title)
if book is not None and book.available:
book.available = False
print(f"{book.title} has been borrowed.")
elif book is not None and not book.available:
print(f"{book.title} is not available for borrowing.")
else:
print(f"{title} is not found in the library.")
def return_book(self, title):
book = self.find_book(title)
if book is not None and not book.available:
book.available = True
print(f"{book.title} has been returned.")
elif book is not None and book.available:
print(f"{book.title} cannot be returned as it was not borrowed.")
else:
print(f"{title} is not found in the library.")
# Example usage:
library = Library()
library.add_book("The Great Gatsby", "F. Scott Fitzgerald", "9780743273565")
library.add_book("To Kill a Mockingbird", "Harper Lee", "9780446310789")
library.add_book("1984", "George Orwell", "9780451524935")
library.list_books()
# Output: The Great Gatsby, To Kill a Mockingbird, 1984
library.borrow_book("The Great Gatsby")
# Output: The Great Gatsby has been borrowed.
library.borrow_book("The Great Gatsby")
# Output: The Great Gatsby is not available for borrowing.
library.return_book("The Great Gatsby")
# Output: The Great Gatsby has been returned.
```
这个代码实现了一个简单的图书管理系统,其中有两个类:`Book` 和 `Library`。`Book` 类表示单个图书,包括标题、作者和ISBN号;`Library` 类表示整个图书馆,包括添加、删除、查找、列出和借还书籍等功能。你可以根据自己的需求进行修改和扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)