用python写一个图书馆馆借阅系统
时间: 2023-08-14 12:04:31 浏览: 139
好的,下面是一个简单的图书馆借阅系统的Python代码:
```python
class Book:
def __init__(self, title, author, genre, isbn):
self.title = title
self.author = author
self.genre = genre
self.isbn = isbn
self.is_borrowed = False
def __str__(self):
return f"{self.title} by {self.author} ({self.genre}), ISBN: {self.isbn}"
class Library:
def __init__(self, name):
self.name = name
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def borrow_book(self, book):
if not book.is_borrowed:
book.is_borrowed = True
print(f"You have borrowed {book}.")
else:
print(f"{book} is already borrowed.")
def return_book(self, book):
if book in self.books:
if book.is_borrowed:
book.is_borrowed = False
print(f"You have returned {book}.")
else:
print(f"{book} is not borrowed.")
else:
print(f"{book} is not part of the library.")
def available_books(self):
available = [book for book in self.books if not book.is_borrowed]
if len(available) == 0:
print("No books available.")
else:
print("Available books:")
for book in available:
print(book)
def main():
library = Library("My Library")
book1 = Book("The Catcher in the Rye", "J.D. Salinger", "Fiction", "0316769177")
book2 = Book("To Kill a Mockingbird", "Harper Lee", "Fiction", "0446310786")
book3 = Book("1984", "George Orwell", "Fiction", "0451524934")
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
library.available_books()
library.borrow_book(book1)
library.borrow_book(book1)
library.borrow_book(book2)
library.return_book(book1)
library.return_book(book3)
library.available_books()
if __name__ == "__main__":
main()
```
这个简单的图书馆馆借阅系统包含两个类:`Book` 和 `Library`。`Book` 类表示一本书,包括书名、作者、类型和 ISBN 等信息,以及一个标志表示书是否被借出。`Library` 类表示一个图书馆,包含图书馆的名字和所有的书籍。它还有一些方法,可以添加、删除、借出和归还书籍,以及列出可用的书籍。
在 `main()` 函数中,我们创建了一个名为 `My Library` 的新图书馆,添加了三本书,并尝试借出和归还一些书籍。最后,我们列出了可用的书籍。
阅读全文