简单的图书馆借阅系统python
时间: 2024-09-13 12:13:30 浏览: 29
一个简单的图书馆借阅系统可以用Python实现,其中包含几个基本功能,例如添加图书、借出图书、归还图书以及查看当前的图书列表。下面是一个简单的示例代码来展示如何构建这样的系统:
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.borrowed = False
def __str__(self):
return f"{self.title} by {self.author}, ISBN: {self.isbn}"
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def borrow_book(self, isbn):
for book in self.books:
if book.isbn == isbn and not book.borrowed:
book.borrowed = True
return f"Book '{book.title}' has been borrowed."
elif book.isbn == isbn and book.borrowed:
return f"Book '{book.title}' is already borrowed."
return "Book not found."
def return_book(self, isbn):
for book in self.books:
if book.isbn == isbn and book.borrowed:
book.borrowed = False
return f"Book '{book.title}' has been returned."
return "Book not found."
def list_books(self):
if not self.books:
return "No books in the library."
for book in self.books:
status = "Available" if not book.borrowed else "Borrowed"
print(f"{book} - {status}")
# 使用示例
library = Library()
library.add_book(Book("Python Programming", "John Doe", "123456789"))
library.add_book(Book("Learning AI", "Jane Smith", "987654321"))
library.list_books() # 列出所有图书
print(library.borrow_book("123456789")) # 借出图书
library.list_books() # 再次列出所有图书以确认状态
print(library.return_book("123456789")) # 归还图书
library.list_books() # 最后列出所有图书以确认状态
```
这个简单的图书馆借阅系统定义了两个类:`Book` 和 `Library`。`Book` 类用来创建图书对象,包含书名、作者、ISBN号和借阅状态。`Library` 类用来管理图书,包括添加图书、借出图书、归还图书和列出所有图书的方法。
阅读全文