优秀代码记录
类
记录集合类
重写iter next实现惰性加载
class MockDataSource:
"""模拟数据源,用于测试"""
def __init__(self, data):
self.data = iter(data)
def __iter__(self):
return self
def __next__(self):
return next(self.data)
class RecordCollection:
"""记录集合类,支持惰性加载和缓存"""
def __init__(self, rows):
self._rows = iter(rows)
self._all_rows = []
self.pending = True
def __len__(self):
return len(self._all_rows)
def __iter__(self):
"""遍历所有行,仅在必要时消耗底层生成器"""
i = 0
while True:
if i < len(self):
yield self[i]
else:
try:
yield next(self)
except StopIteration:
return
i += 1
def __getitem__(self, index):
"""获取指定索引的记录"""
return self._all_rows[index]
def __next__(self):
try:
nextrow = next(self._rows)
self._all_rows.append(nextrow)
return nextrow
except StopIteration:
self.pending = False
raise StopIteration("RecordCollection contains no more rows.")
def test_record_collection():
# 测试数据
test_data = [
{"id": 1, "name": "张三"},
{"id": 2, "name": "李四"},
{"id": 3, "name": "王五"}
]
# 创建数据源和记录集合
data_source = MockDataSource(test_data)
records = RecordCollection(data_source)
print("测试1:逐个获取数据")
print(f"当前缓存大小: {len(records)}") # 应该是 0
# 获取第一条记录
first_record = next(records)
print(f"第一条记录: {first_record}")
print(f"当前缓存大小: {len(records)}") # 应该是 1
print("\n测试2:使用for循环遍历")
for record in records:
print(f"读取记录: {record}")
print(f"\n遍历后缓存大小: {len(records)}") # 应该是 3
print(f"是否还有待处理数据: {records.pending}") # 应该是 False
print("\n测试3:再次遍历(从缓存读取)")
for record in records:
print(f"{record}")
if __name__ == "__main__":
test_record_collection()