Python双头队列实现缓存环
与上一篇文章类似,本文通过从collections.dequeue派生出一个子类,这个类型提供了“双头队列——因而从任意一头添加或删除数据的效率都非常高。
[root@xiaoxiong cb6]# cat cb2_6_11_exm_3.py from collections import dequeclass RingBuffer(deque): def __init__(self, size_max): deque.__init__(self) self.size_max = size_max def _full_append(self, datum): deque.append(self, datum) self.popleft() def append(self, datum): deque.append(self, datum) if len(self) == self.size_max: self.append = self._full_append def tolist(self): return list(self)if __name__ == '__main__': print 'hallo' x = RingBuffer(5) print x.tolist() x.append(1); x.append(2); x.append(3); x.append(4) print x.tolist() print x.append(5) print x.tolist() print x.append(6) print x.tolist() print x.append(7) print x.tolist()[root@xiaoxiong cb6]# python cb2_6_11_exm_3.py hallo[][1, 2, 3, 4]None[1, 2, 3, 4, 5]None[2, 3, 4, 5, 6]None[3, 4, 5, 6, 7][root@xiaoxiong cb6]#