![](/img/trans.png)
[英]attribute 'maxlen' of 'collections.deque' objects is not writable
[英]Change maxlen attribute of collections.deque
我最近一直在做一个小项目,其中collections.deque
的maxlen
属性是根据用户可配置的参数设置的。 State 存储在会话之间; 此 state 的任何活动deque
forms 部分。 因此,如果会话之间有配置更改,则需要更改每个恢复的deque
的maxlen
属性。 目前,我正在这样做:
if current_setting != last_setting:
# Deques are in a dictionary
for k in dictionary:
# Other data types and structures exist in this dictionary
if dictionary[k].__class__() == deque():
dictionary[k] = deque([*dictionary[k]], maxlen=current_setting)
创建一个新的deque
并将旧的解包到其中似乎效率低下。 我的问题是是否有;
deque
的maxlen
属性值的方法,或者,如果这是不可能的/不明智的;正如CKM 的评论所说,更改maxlen
是不可能的,因为它是一个只读属性。
>>> d = deque("abcdefghij", maxlen=10)
>>> len(d)
10
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], maxlen=10)
>>> d.maxlen = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: attribute 'maxlen' of 'collections.deque' objects is not writable
为了更改maxlen
,您必须使用正确的maxlen
创建一个新的deque
object ,如下所示:
>>> NEW_MAX_LENGTH = 3
>>> d = deque("abcdefghij", maxlen=10)
>>> d2 = deque(d, maxlen=NEW_MAX_LENGTH)
>>> d2
deque(['h', 'i', 'j'], maxlen=3)
有关更多信息,请参阅Python 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.