我将让下面的终端会话自圆其说:

>>> import shelve
>>> s = shelve.open('TestShelve')
>>> from collections import deque
>>> s['store'] = deque()
>>> d = s['store']
>>> print s['store']
deque([])
>>> print d
deque([])
>>> s['store'].appendleft('Teststr')
>>> d.appendleft('Teststr')
>>> print s['store']
deque([])
>>> print d
deque(['Teststr'])

ds['store']不应该指向同一个对象吗?为什么appendleftd上工作而不是在s['store']上?

最佳答案

结果发现它们不一样,所以对它们执行的任何操作都不匹配:

>>> import shelve
>>> s = shelve.open('TestShelve')
>>> from collections import deque
>>> s['store'] = deque()
>>> d = s['store']
>>> id(s['store'])
27439296
>>> id(d)
27439184

要在编码时修改项,需要传递参数writeback=True
s = shelve.open('TestShelve', writeback=True)

请参阅文档:
如果writeback参数为True,则对象将保存
在同步和关闭时访问所有条目并将其写回dict
时代。这允许对可变条目进行自然操作,但可以
消耗更多的内存,使同步和关闭需要很长时间。
您也可以使用writeback=False来完成这项工作,但是您需要完全按照提供的示例编写代码:
# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

关于python - 试图将双端队列存储在架子上的怪异行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11145951/

10-08 20:42