代码记录
@ 晚风 · Tuesday, Feb 25, 2025 · 1 分钟阅读 · 更新于 2月 25, 2025

优秀代码记录

记录集合类

重写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()

关于我

❤️

姓名: lwz


性别: 男


年龄: 29


星座: 摩羯座


职业: python工程师


爱好: 秋、ps5、运动


主要的技术栈是:

  • python
  • 自动驾驶仿真验证

学习网站: leetcode


公司: 国科础石


– 2025 年 2 月 25 日更新

我的一些开源项目

等等?项目呢?不会没有吧??

其他

如果你喜欢我的开源项目或者它们可以给你带来帮助,可以赏一杯咖啡 ☕ 给我。~

It is better to attach some information or leave a message so that I can record the donation 📝, thank you very much 🙏.

社交链接