利用python写一个图书管理系统
时间: 2023-12-06 18:04:40 浏览: 85
好的,下面是一个简单的图书管理系统的代码示例,你可以根据自己的需求进行修改和完善。
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.checked_out = False
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 remove_book(self, book):
self.books.remove(book)
def search_books(self, title=None, author=None, isbn=None):
results = []
for book in self.books:
if title and title.lower() in book.title.lower():
results.append(book)
elif author and author.lower() in book.author.lower():
results.append(book)
elif isbn and isbn == book.isbn:
results.append(book)
return results
def check_out(self, book):
if not book.checked_out:
book.checked_out = True
return True
else:
return False
def check_in(self, book):
if book.checked_out:
book.checked_out = False
return True
else:
return False
# 示例代码
if __name__ == "__main__":
library = Library()
book1 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", "9780345391803")
book2 = Book("1984", "George Orwell", "9780451524935")
book3 = Book("To Kill a Mockingbird", "Harper Lee", "9780446310789")
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
results = library.search_books(title="the")
for result in results:
print(result)
library.check_out(book1)
print(book1.checked_out)
library.check_in(book1)
print(book1.checked_out)
```
这个图书管理系统包含两个类,一个是 `Book` 类,用于表示一本书的基本信息和是否被借出,另一个是 `Library` 类,用于管理所有的书籍,包括添加、删除、搜索、借出和归还等功能。在示例代码中,我们先创建了三本书,然后添加到图书馆中,接着通过关键字搜索图书,借出其中一本书并检查它的借出状态,最后归还该书并再次检查它的借出状态。
阅读全文