Python双头行列实现缓存环

Python双头队列实现缓存环


与上一篇文章类似,本文通过从collections.dequeue派生出一个子类,这个类型提供了“双头队列——因而从任意一头添加或删除数据的效率都非常高。


[root@xiaoxiong cb6]# cat cb2_6_11_exm_3.py 
from collections import deque
class 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]# 

该程序比较巧妙的地方在于当队列满时,只需要切换append方法,这样的话比类切换更为方便。所有的操作在类中作了完整的封装,不须要在调用实例之前判断调用哪个方法,这种切换实例的两个方法的编程技巧相当方便。