3、 改造读者管理模块,将读者列表页面改造成分页查询方式。 第一步:自行设计PageData类,用于存放分页数据 第二步:改造ReaderManager类,将其中的查询读者方法改造成分页查询。 第三步(选做):修改ui类,增加上一页、下一页按钮,实现读者的分页查询,要求每页20人 【实验结果与分析】 A、 PageData类代码。 B、 给出改造后ReaderManager类的方法代码。 C、 给出ui类中的修改部分(注:生成表格的方法需做微调)
时间: 2023-11-22 17:56:38 浏览: 104
3、用户模块-日志管理-多条件的查询分页操作-代码编写
A、PageData类代码:
```python
class PageData:
def __init__(self, data_list, current_page, page_size):
self.data_list = data_list # 数据列表
self.current_page = current_page # 当前页数
self.page_size = page_size # 每页大小
self.total_pages = (len(data_list) + page_size - 1) // page_size # 总页数
def get_data(self):
start_idx = (self.current_page - 1) * self.page_size
end_idx = start_idx + self.page_size
return self.data_list[start_idx:end_idx]
```
B、改造后的ReaderManager类方法代码:
```python
class ReaderManager:
def __init__(self):
self.__readers = []
def add_reader(self, reader):
self.__readers.append(reader)
def remove_reader(self, reader_id):
for reader in self.__readers:
if reader.id == reader_id:
self.__readers.remove(reader)
return reader
def find_reader_by_id(self, reader_id):
for reader in self.__readers:
if reader.id == reader_id:
return reader
def find_readers_by_name(self, name):
result = []
for reader in self.__readers:
if reader.name == name:
result.append(reader)
return result
def find_readers_by_age(self, age):
result = []
for reader in self.__readers:
if reader.age == age:
result.append(reader)
return result
def find_readers_by_gender(self, gender):
result = []
for reader in self.__readers:
if reader.gender == gender:
result.append(reader)
return result
def get_readers_by_page(self, page_num):
page_size = 20
start_idx = (page_num - 1) * page_size
end_idx = start_idx + page_size
return PageData(self.__readers[start_idx:end_idx], page_num, page_size)
```
C、ui类中的修改部分:
```python
class ReaderUI:
def __init__(self):
self.manager = ReaderManager()
# 省略其他方法...
def show_reader_list(self):
page_num = 1
while True:
page_data = self.manager.get_readers_by_page(page_num)
reader_list = page_data.get_data()
print("\n读者列表:")
print("{:5s}\t{:20s}\t{:3s}\t{:4s}\t{:10s}".format("ID", "姓名", "年龄", "性别", "电话"))
for reader in reader_list:
print("{:5d}\t{:20s}\t{:3d}\t{:4s}\t{:10s}".format(reader.id, reader.name, reader.age, reader.gender,
reader.tel))
# 分页操作
if page_num > 1:
print("\n上一页(P),", end="")
if page_num < page_data.total_pages:
print("下一页(N)", end="")
print(",退出(Q)")
op = input("请选择操作:")
if op == "P" and page_num > 1:
page_num -= 1
elif op == "N" and page_num < page_data.total_pages:
page_num += 1
elif op == "Q":
break
```
阅读全文