定义两个类 Book, BookDAO, 其中Book类用于封装一个书籍对象,BookDAO中实现对于文本文件Book.txt的增加、修改、删除和查询方法(至少4种查询方法)
时间: 2024-11-09 08:22:37 浏览: 49
在面向对象编程中,我们可以创建两个类来分别处理书籍的对象和数据库操作。这里是一个简单的示例,使用Python来实现这个场景:
```python
class Book:
def __init__(self, title, author, id=None):
self.title = title
self.author = author
self.id = id
def __str__(self):
return f"ID: {self.id}, Title: {self.title}, Author: {self.author}"
class BookDAO:
def __init__(self, filename="Book.txt"):
self.filepath = filename
self.data = {} # 初始时假设数据存储在一个字典中,实际应用可能需要读取文件或数据库初始化
# 增加方法
def add_book(self, book):
book.id = len(self.data) + 1
self.data[book.id] = book
with open(self.filepath, 'a') as file:
file.write(f"{book}\n")
# 修改方法
def update_book(self, book_id, updated_book):
if book_id in self.data:
self.data[book_id] = updated_book
with open(self.filepath, 'w') as file:
for id_, book in self.data.items():
file.write(str(book))
file.write("\n")
else:
print("Book not found.")
# 删除方法
def delete_book(self, book_id):
if book_id in self.data:
del self.data[book_id]
with open(self.filepath, 'w') as file:
for id_, book in self.data.items():
file.write(str(book))
file.write("\n")
else:
print("Book not found.")
# 查询方法
def get_book_by_id(self, book_id):
if book_id in self.data:
return self.data.get(book_id)
else:
return None
def search_by_title(self, title):
return [book for book in self.data.values() if book.title == title]
def search_by_author(self, author):
return [book for book in self.data.values() if book.author == author]
# 使用示例
book1 = Book("Python Crash Course", "Eric Matthes")
bookDAO = BookDAO()
bookDAO.add_book(book1)
print(bookDAO.get_book_by_id(1)) # 查找id为1的书
books_by_title = bookDAO.search_by_title("Python Crash Course") # 搜索标题包含"Python Crash Course"的书
```
在这个例子中,`Book`类代表单个书籍对象,而`BookDAO`类包含了针对`Book.txt`文件的操作方法,包括添加、更新、删除和各种查询方法。
阅读全文