Posted on 2020-09-07 15:48
魔のkyo 阅读(230)
评论(0) 编辑 收藏 引用 所属分类:
Programming 、
Python
# -*- 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)