属性' maxlen' of' collections.deque'对象不可写

时间:2016-01-01 18:13:21

标签: python python-3.x collections deque

class TailDeque(collections.deque):
    '''Implementation of deque with limited maxlen support for Python 2.5.'''
    def __init__(self, iterable=None, maxlen=-1):
        super(TailDeque, self).__init__([])
        self.maxlen = maxlen
        if iterable is not None:
            self.extend(iterable)

    def extend(self, iterable):
        for item in iterable:
            self.append(item)

    def extendleft(self, iterable):
        for item in iterable:
            self.appendleft(item)

    def appendleft(self, item):
        if len(self) == self.maxlen:
            self.pop()
        super(TailDeque, self).appendleft(item)    

    def append(self, item):
        if len(self) == self.maxlen:
            self.popleft()
        super(TailDeque, self).append(item)
logQueue = TailDeque(maxlen=20)

有人可以解释并告诉我如何为python 3.4做这个吗?

我总是得到

AttributeError: attribute 'maxlen' of 'collections.deque' objects is not writable

https://docs.python.org/2/library/collections.html#deque-objects

1 个答案:

答案 0 :(得分:2)

maxlen参数已添加到2.6和3.0中的collections.deque中。 (从参数设置的只读maxlen属性在2.7和3.1中添加。)您发布的代码用于2.5作为部分替代。对于2.6+和3.1+,你应该只使用collections.deque而不是打扰部分后端。如果要编写支持2.5到2.7的代码,则应在2.5上运行时将collections.deque替换为其包装器。像

这样的东西
import sys

major = sys.version[0:3]

if major >= '2.6':
    from collections import deque
elif major == '2.5':
    from myutils import TailDeque as deque
else:
    raise MyException('This app requires 2.5 or later.')