source1是《python基础教程》上的一个例子,关于shelve模块的,求大侠解释下.

#source1
#from <python基础教程>import shelves = shelve.open('temp.dat')s['x'] = ['a', 'b', 'c']s['x'].append('d')print s['x']
--------------------------
>>>['a', 'b', 'c']
书上的解释:1.列表['a', 'b', 'c']存储在x下;
2.获得存储的表示, 并且根据它创建新的列表,而'd'加到这个副本.修改的版本还没有被保存!
3.最终,再次获得原始版本----没有'd'
第2条没想明白,为什么会创建新的列表.(source3中为什么没创建,或者说为什么与source3的结果不一样.)
========================
#source2
import shelves = shelve.open('temp.dat')s['x'] = ['a', 'b', 'c']
s. close()
s = shelve.open('temp.dat')
s['x'].append('d')print s['x']
--------------------------
>>>['a', 'b', 'c']
这条是看到别的大神有说是因为s['x'] = ['a', 'b', 'c']这条执行完后没有写回,
s. close()是确保其结果写回.那s['x'].append('d')结果为什么还是和source1一样.
=======================
#source3
s = {}s['x'] = ['a', 'b', 'c']s['x'].append('d')print s['x']
-------------------------
>>>['a', 'b', 'c', 'd']
#source3格式修正
s = {}
s['x'] = ['a', 'b', 'c']
s['x'].append('d')
print s['x']
-------------------------
>>>['a', 'b', 'c', 'd']

Python文档中有提到这一点(详见shelve模块文档):
Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf.


大致意思如下:
一个shelf(对象)无法知道什么时候其中一个可变的项被修改了。默认情况下,一个被修改过的对象只有重新赋给shelf对象,这些更改才会生效。


Python文档中也给出了两种解决方案:


第一种:
把修改过的对象赋给shelve对象:

s['x'] = s['x'].append('d')

或者,更清晰的形式:

temp = s['x'] # 得到s['x']的拷贝,即一个mutable的列表对象
temp.append('d') # 在这个列表对象上进行append操作
s['x'] = temp # 重新写回去

第二种:

s = shelve.open('temp.dat', writeback = True) # 指定writeback为True,默认为False
s['x'] = ['a', 'b', 'c']
s['x'].append('d')
s.close()

这样,你要访问的entry就会cached in memory,并在你调用sync或close方法的时候写入文件。

温馨提示:答案为网友推荐,仅供参考
相似回答