图书馆代码python
时间: 2023-07-22 08:43:59 浏览: 87
以下是一个简单的图书馆代码Python实现的示例:
```python
class Book:
def __init__(self, title, author, ISBN, available=True):
self.title = title
self.author = author
self.ISBN = ISBN
self.available = available
def __str__(self):
return f"{self.title} by {self.author}"
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def search_by_title(self, title):
results = []
for book in self.books:
if book.title.lower() == title.lower():
results.append(book)
return results
def search_by_author(self, author):
results = []
for book in self.books:
if book.author.lower() == author.lower():
results.append(book)
return results
def search_by_isbn(self, isbn):
results = []
for book in self.books:
if book.ISBN == isbn:
results.append(book)
return results
def checkout_book(self, title):
for book in self.books:
if book.title.lower() == title.lower() and book.available:
book.available = False
return True
return False
def checkin_book(self, title):
for book in self.books:
if book.title.lower() == title.lower() and not book.available:
book.available = True
return True
return False
```
使用示例:
```python
# 创建几本书
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "9780743273565", True)
book2 = Book("To Kill a Mockingbird", "Harper Lee", "9780446310789", True)
book3 = Book("Pride and Prejudice", "Jane Austen", "9780486284736", True)
# 创建一个图书馆并添加书籍
library = Library()
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
# 通过标题查找书籍
results = library.search_by_title("To Kill a Mockingbird")
for book in results:
print(book)
# 借出一本书
if library.checkout_book("To Kill a Mockingbird"):
print("Book checked out!")
else:
print("Book not available.")
# 归还一本书
if library.checkin_book("To Kill a Mockingbird"):
print("Book checked in!")
else:
print("Book not checked out.")
```
希望这个简单的示例对你有所帮助。
阅读全文