python实现通过shelve修改对象实例,pythonshelve


本文实例讲述了python实现通过shelve修改对象的方法,分享给大家供大家参考。

具体实现方法如下:

import shelve
she = shelve.open('try.she','c')
for c in 'spam':
  she[c] = {c:23}
  
for c in she.keys():
  print c,she[c]


she.close()


she = shelve.open('try.she','c')
print she['p']
she['p']['p'] = 42 #这样修改是不行,这只是修改了个临时对象
print she['p']


a = she['p']#给临时对象绑定个名字
a['p'] = 42
she['p'] = a
print she['p']

本文实例测试环境为Python2.7.6

程序运行结果如下:

p {'p': 23}
a {'a': 23}
m {'m': 23}
s {'s': 23}
{'p': 23}#原值是这样的
{'p': 23}#只是修改了临时对象
{'p': 42}#绑定名字后,达到修改的目的

实例代码及运行结果均配有较为详尽的注释,帮助大家理解其含义。希望本文所述对大家的Python程序设计有所帮助。


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

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,默认为Falses['x'] = ['a', 'b', 'c']s['x'].append('d')s.close()这样,你要访问的entry就会cached in memory,并在你调用sync或close方法的时候写入文件。

 

有关python实例化一个对象的问题

定义一个类封装所有的属性,然后把这个类的对象作为返回值。
不知道是不是你要的意思:

class Node:
def __init__(self, nodes, city, state, description = None):
self.nodes = nodes
self.city = city
self.state = state
self.description = description

def node_by_name(nodes, city, state):
# some other process
description = 'NORTH CAMBRIDGE'
return Node(nodes, city, state, description)

ans = node_by_name('testNode', 'CAMBRIDGE', 'MA')

print ans.state, ans.description
 

评论关闭