帮我生成一个图书管理借书,还书的python代码
时间: 2024-02-05 16:02:40 浏览: 143
图书管理系统python代码
5星 · 资源好评率100%
好的,以下是一个简单的图书管理系统的Python代码:
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.available = True
def __str__(self):
return f"{self.title} by {self.author}"
def check_out(self):
self.available = False
def check_in(self):
self.available = True
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def search_book(self, search_term):
results = []
for book in self.books:
if search_term.lower() in book.title.lower() or search_term.lower() in book.author.lower():
results.append(book)
return results
def check_out_book(self, book):
if book.available:
book.check_out()
print(f"{book} has been checked out.")
else:
print(f"{book} is not available.")
def check_in_book(self, book):
if not book.available:
book.check_in()
print(f"{book} has been checked in.")
else:
print(f"{book} has already been checked in.")
```
这个系统包括两个类:Book和Library。Book类表示一本书,它有一个标题,作者和ISBN号。它还有一个可用属性,表示这本书是否可用。Library类表示整个图书馆,它有一个书本列表,可以添加,删除和搜索书籍。它还有一个check_out_book方法和check_in_book方法,用于借书和还书。
你可以通过以下方式使用这个系统:
```python
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565")
book2 = Book("To Kill a Mockingbird", "Harper Lee", "978-0446310789")
book3 = Book("1984", "George Orwell", "978-0451524935")
library = Library()
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
results = library.search_book("Orwell")
print("Search results:")
for book in results:
print(book)
library.check_out_book(book3)
library.check_out_book(book3)
library.check_in_book(book3)
library.check_in_book(book3)
```
这将输出以下内容:
```
Search results:
1984 by George Orwell
1984 has been checked out.
1984 is not available.
1984 has been checked in.
1984 has already been checked in.
```
阅读全文