gpt4 book ai didi

python - 'maxlen' 对象的属性 'collections.deque' 不可写

转载 作者:行者123 更新时间:2023-12-01 04:13:47 28 4
gpt4 key购买 nike

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

最佳答案

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.')

关于python - 'maxlen' 对象的属性 'collections.deque' 不可写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34558697/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com