python 图书管理系统 代码
时间: 2023-09-27 17:05:57 浏览: 124
Python实现简易图书管理系统
### 回答1:
下面是一个简单的 Python 图书管理系统的代码示例:
```python
# 定义图书类
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
# 定义图书管理器类
class BookManager:
def __init__(self):
self.books = []
# 添加图书
def add_book(self, book):
self.books.append(book)
# 删除图书
def delete_book(self, book):
self.books.remove(book)
# 查询图书
def search_book(self, title):
for book in self.books:
if book.title == title:
return book
return None
# 显示所有图书
def show_all_books(self):
for book in self.books:
print(f'《{book.title}》 by {book.author} : ${book.price}')
# 创建图书管理器对象
book_manager = BookManager()
# 创建图书对象并添加到图书管理器中
book1 = Book('图书1', '作者1', 100)
book_manager.add_book(book1)
book2 = Book('图书2', '作者2', 200)
book_manager.add_book(book2)
book3 = Book('图书3', '作者3', 300)
book_manager.add_book(book3)
# 显示所有图书
book_manager.show_all_books()
# 搜索图书
book = book_manager.search_book('图书2')
if book is not None:
print(f'找到了《{book.title}》这本书')
else:
print('没有找到这本书')
# 删除图书
book_manager.delete_book(book2)
# 再次显示所有图书
book_manager.show_all_books()
```
这个图书管理系统实现了图书的增加、删除、查询和显示功能。首先定义了 `Book` 类表
### 回答2:
Python图书管理系统代码实例如下:
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
print("图书添加成功!")
def remove_book(self, book):
if book in self.books:
self.books.remove(book)
print("图书删除成功!")
else:
print("图书不存在!")
def search_book(self, keyword):
found_books = []
for book in self.books:
if keyword.lower() in book.title.lower() or keyword.lower() in book.author.lower():
found_books.append(book)
if len(found_books) > 0:
print("以下是您搜索到的图书:")
for book in found_books:
print(f"标题:{book.title},作者:{book.author}")
else:
print("未找到相关图书!")
def main():
library = Library()
book1 = Book("Python入门教程", "张三")
library.add_book(book1)
book2 = Book("Python高级编程", "李四")
library.add_book(book2)
book3 = Book("数据结构与算法", "王五")
library.add_book(book3)
library.search_book("python")
if __name__ == "__main__":
main()
```
以上代码定义了一个图书类Book,包含了书名和作者信息。图书馆类Library包含了添加图书、删除图书和搜索图书等功能。在main函数中,创建了一个图书馆对象,并添加了三本书。最后进行了一次以关键字"python"进行搜索的操作。
阅读全文