posts - 225, comments - 62, trackbacks - 0, articles - 0
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
# -*- coding: utf-8 -*-

class RollArray:
    class Iterator:
        def __init__(self, subject):
            self.subject = subject
            self.start = self.subject.idx
            self.i = 0

        def __next__(self):
            while self.i < self.subject.capability:
                if self.start + self.i in self.subject:
                    o = self.subject[self.start + self.i]
                    self.i += 1
                    return o
                else:
                    self.i += 1
            raise StopIteration()

    def __init__(self, capability, items=[]):
        self.data = [None] * capability
        self.used = [False] * capability
        self.idx = 0
        self.capability = capability
        for e in items:
            self.append(e)

    def append(self, obj):
        self.data[self.idx] = obj
        self.used[self.idx] = True
        self.idx = (self.idx + 1) % 10

    # 重载 for e in x:
    def __iter__(self):
        return RollArray.Iterator(self)

    # 重载 [] const
    def __getitem__(self, i):
        if self.used[i%self.capability]:
            return self.data[i%self.capability]
        else:
            raise IndexError()

    # 重载 []
    def __setitem__(self, i, v):
        self.data[i%self.capability] = v
        self.used[i%self.capability] = True
        return v

    # 重载 del x[]
    def __delitem__(self, i):
        self.used[i%self.capability] = False

    # 重载 if e in x:
    def __contains__(self, i):
        return self.used[i%self.capability]

    def tolist(self):
        l = []
        for e in self:
            l.append(e)
        return l

    def __repr__(self):
        return f"{self.__class__.__name__}({self.capability}, items={self.tolist()})"


if __name__ == '__main__':
    arr = RollArray(10, range(5))
    del arr[3]
    print(arr)

    for i in range(5, 11):
        arr.append(i)

    print(arr)

    arr[11] = 11
    print(arr)

    for e in arr:
        print(e)
只有注册用户登录后才能发表评论。