我有一个小班:
import pickle
import shelve
class Base:
def __init__(self, userid, username, pic_list=[]):
self.userid=userid
self.pic_list=pic_list
self.username_list=[username]
self.username=self.username_list[-1]
def pic_add(self, pic):
self.pic_list.append(pic)
if __name__ == '__main__':
path="D:/"
db = shelve.open(path+'test_base')
db['111']=Base('111','111name',[4,5,6])
db['111'].pic_add('123dsf')
print (sorted(db['111'].pic_list))
db.close()
我想将123dsf
追加到类实例的pic_list
" 111"。但我得到的结果是:
[4, 5, 6]
[Finished in 0.3s]
我想收到[4,5,6,123dsf]。我做错了什么?
感谢名单。
P.S。提示 - 这是搁置模块语法,' cos添加' y'工作正常:
db['111']=Base('111','111name',[4,5,6])
db['111'].pic_add('123dsf')
Base.pic_add(db['111'],'123dsf')
y=Base('222','222name',[7,8,9])
y.pic_add('pis')
print (y.pic_list)
print (sorted(db['111'].pic_list))
结果是:
[7, 8, 9, 'pis']
[4, 5, 6]
[Finished in 0.4s]
答案 0 :(得分:2)
两种方法 - 正如文档中提出的那样:https://docs.python.org/2/library/shelve.html#shelve-example
1。设置writeback
标志:
db = shelve.open(path+'test_base', writeback=True)
允许你改变对象:
db['111'].pic_add('123dsf')
2. 检索存储对象的副本,然后改变副本,然后存储副本:
cpy = db['111']
cpy.pic_add('123dsf')
db['111'] = cpy