编写借阅和归还图书代码
时间: 2023-07-03 18:21:23 浏览: 129
当然,以下是一个简单的Python图书管理系统示例,包含借阅和归还图书的代码:
```python
class Book:
def __init__(self, id, title, author, is_available=True):
self.id = id
self.title = title
self.author = author
self.is_available = is_available
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def search_book_by_id(self, id):
for book in self.books:
if book.id == id:
return book
return None
class Member:
def __init__(self, name):
self.name = name
self.borrowed_books = []
def borrow_book(self, book):
if book.is_available:
book.is_available = False
self.borrowed_books.append(book)
print("Book with ID", book.id, "has been borrowed by", self.name)
else:
print("Book with ID", book.id, "is not available for borrowing")
def return_book(self, book):
if book in self.borrowed_books:
book.is_available = True
self.borrowed_books.remove(book)
print("Book with ID", book.id, "has been returned by", self.name)
else:
print("Book with ID", book.id, "is not borrowed by", self.name)
# 创建图书馆和图书
library = Library()
book1 = Book(1, "Python for Beginners", "John Smith")
book2 = Book(2, "Advanced Python Programming", "Jane Doe")
library.add_book(book1)
library.add_book(book2)
# 创建会员并借阅和归还图书
member1 = Member("Alice")
member1.borrow_book(book1)
member1.borrow_book(book2)
member1.return_book(book1)
member1.return_book(book2)
```
运行此代码将创建一个图书馆和两本书。创建一个名为“Alice”的会员,然后借阅两本书并将它们归还。
阅读全文