用python写一个图书管理系统,且有代码注释
时间: 2024-03-07 16:50:37 浏览: 154
好的,以下是用Python实现的图书管理系统:
```python
# 图书管理系统
# 定义一个图书类
class Book:
def __init__(self, book_id, title, author, publisher, publish_date):
self.book_id = book_id
self.title = title
self.author = author
self.publisher = publisher
self.publish_date = publish_date
# 定义一个图书管理系统类
class Library:
def __init__(self):
self.books = []
# 添加图书
def add_book(self, book):
self.books.append(book)
# 删除图书
def remove_book(self, book_id):
for book in self.books:
if book.book_id == book_id:
self.books.remove(book)
return True
return False
# 查找图书
def search_book(self, keyword):
result = []
for book in self.books:
if keyword in book.title or keyword in book.author or keyword in book.publisher:
result.append(book)
return result
# 显示所有图书
def display_books(self):
for book in self.books:
print("ID: {}, Title: {}, Author: {}, Publisher: {}, Publish Date: {}".format(book.book_id, book.title, book.author, book.publisher, book.publish_date))
# 测试程序
# 创建一个图书管理系统对象
library = Library()
# 添加图书
book1 = Book(1, "Python入门教程", "张三", "人民邮电出版社", "2020-01-01")
book2 = Book(2, "Java编程思想", "李四", "机械工业出版社", "2020-02-01")
book3 = Book(3, "C++程序设计", "王五", "清华大学出版社", "2020-03-01")
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
# 显示所有图书
library.display_books()
# 删除图书
library.remove_book(2)
# 显示所有图书
library.display_books()
# 查找图书
result = library.search_book("Python")
for book in result:
print("ID: {}, Title: {}, Author: {}, Publisher: {}, Publish Date: {}".format(book.book_id, book.title, book.author, book.publisher, book.publish_date))
```
这个程序实现了一个简单的图书管理系统,具有添加、删除、查找、显示所有图书的功能。通过定义`Book`类和`Library`类来实现,其中`Library`类维护了一个`books`列表来存储所有的图书对象。在测试程序中,我们创建一个`Library`对象,添加三本图书,并展示所有图书。接着,我们删除了一本图书并再次展示所有图书。最后,我们查找包含关键字“Python”的图书,并展示结果。
希望这个程序对你有帮助!
阅读全文