gpt4 book ai didi

Python惰性列表

转载 作者:太空狗 更新时间:2023-10-29 17:17:08 27 4
gpt4 key购买 nike

我想创建我自己的集合,它具有 python 列表的所有属性,并且还知道如何将自身保存到数据库中/从数据库中加载自身。此外,我想让加载隐式和惰性,因为它不会在创建列表时发生,而是等到第一次使用时发生。

是否有一个单一的__xxx__方法我可以覆盖以在第一次使用任何列表属性(例如lengetitem)时加载列表,iter...等)而不必全部覆盖它们?

最佳答案

不是单个,但 5 个就足够了:

from collections import MutableSequence

class Monitored(MutableSequence):
    def __init__(self):
        super(Monitored, self).__init__()
        self._list = []

    def __len__(self):
        r = len(self._list)
        print "len: {0:d}".format(r)
        return r

    def __getitem__(self, index):
        r = self._list[index]
        print "getitem: {0!s}".format(index)
        return r

    def __setitem__(self, index, value):
        print "setitem {0!s}: {1:s}".format(index, repr(value))
        self._list[index] = value

    def __delitem__(self, index):
        print "delitem: {0!s}".format(index)
        del self._list[index]

    def insert(self, index, value):
        print "insert at {0:d}: {1:s}".format(index, repr(value))
        self._list.insert(index, value)

检查某物是否实现了整个列表接口(interface)的正确方法是检查它是否是 MutableSequence 的子类。在 collections 模块中找到的 ABCs,其中 MutableSequence 是一个,存在的原因有两个:

  1. 允许您创建自己的类来模拟内部容器类型,以便它们可以在普通内置容器所在的任何地方使用。

  2. 用作 isinstanceissubclass 的参数来验证对象是否实现了必要的功能:

>>> isinstance([], MutableSequence)
True
>>> issubclass(list, MutableSequence)
True

我们的 Monitored 类是这样工作的:

>>> m = Monitored()>>> m.append(3)len: 0insert at 0: 3>>> m.extend((1, 4))len: 1insert at 1: 1len: 2insert at 2: 4>>> m.l[3, 1, 4]>>> m.remove(4)getitem: 0getitem: 1getitem: 2delitem: 2>>> m.pop(0)   # after this, m.l == [1]getitem: 0delitem: 03>>> m.insert(0, 4)insert at 0: 4>>> m.reverse()   # After reversing, m.l == [1, 4]len: 2getitem: 1getitem: 0setitem 0: 1setitem 1: 4>>> m.index(4)getitem: 0getitem: 11

关于Python惰性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/241141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com