在 Python 中修改 class 个实例
Modifying class instances in Python
我有一个小class:
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
附加到 class 实例“111”的 pic_list
。但是我得到的结果是:
[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]
两种方法 - 如文档中所建议: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
我有一个小class:
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
附加到 class 实例“111”的 pic_list
。但是我得到的结果是:
[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]
两种方法 - 如文档中所建议: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