定义一个图书类,有id,name,price,author,type,press,,在测试类里实现添加到book.txt文件中,实现查询功能,删除功能,修改功能
时间: 2024-05-07 09:22:20 浏览: 103
以下是Python语言实现:
```python
# 定义图书类
class Book:
def __init__(self, book_id, name, price, author, book_type, press):
self.book_id = book_id
self.name = name
self.price = price
self.author = author
self.book_type = book_type
self.press = press
# 测试类
class BookManager:
def __init__(self):
self.books = []
self.filename = 'book.txt'
self.load_books()
# 从文件中加载图书信息
def load_books(self):
with open(self.filename, 'r', encoding='utf-8') as f:
for line in f:
book_info = line.strip().split(',')
book = Book(book_info[0], book_info[1], float(book_info[2]), book_info[3], book_info[4], book_info[5])
self.books.append(book)
# 将图书信息保存到文件中
def save_books(self):
with open(self.filename, 'w', encoding='utf-8') as f:
for book in self.books:
f.write(f"{book.book_id},{book.name},{book.price},{book.author},{book.book_type},{book.press}\n")
# 添加图书
def add_book(self, book):
self.books.append(book)
self.save_books()
# 删除图书
def del_book(self, book_id):
for i, book in enumerate(self.books):
if book.book_id == book_id:
self.books.pop(i)
self.save_books()
return True
return False
# 修改图书信息
def modify_book(self, book_id, book):
for i, b in enumerate(self.books):
if b.book_id == book_id:
self.books[i] = book
self.save_books()
return True
return False
# 查询图书信息
def query_book(self, book_id=None, name=None, author=None, book_type=None, press=None):
result = []
for book in self.books:
if book_id and book.book_id != book_id:
continue
if name and book.name != name:
continue
if author and book.author != author:
continue
if book_type and book.book_type != book_type:
continue
if press and book.press != press:
continue
result.append(book)
return result
```
使用方法:
```python
# 创建图书管理器
book_manager = BookManager()
# 添加图书
book1 = Book('001', 'Python编程从入门到实践', 78.80, 'Eric Matthes', '计算机', '人民邮电出版社')
book_manager.add_book(book1)
# 查询图书
result = book_manager.query_book(name='Python编程从入门到实践')
for book in result:
print(book.book_id, book.name, book.price, book.author, book.book_type, book.press)
# 修改图书
book2 = Book('001', 'Python编程从入门到入门', 79.90, 'Eric Matthes', '计算机', '人民邮电出版社')
book_manager.modify_book('001', book2)
# 删除图书
book_manager.del_book('001')
```
阅读全文