Python字典中的类工作

2024-05-15 12:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

对于这个例子,我有一个字典,当我调用它时,“余烬攻击”显示出来。在

#import shelve
class Pokemon():
"""Each pokemon's attributes"""

def __init__(self):
    self.id=[]
    self.var1=[]
    self.var2=[]
    self.var3=[]
    self.var4=[]
    self.var5=[]

def __str__(self):
     showList=['id','var1', 'var2', 'var3', 'var4', 'var5']

#dict1=shelve.open("shelve.dat")
dict1={}
dict1["Charmander"]=Pokemon()
dict1["Charmander"].var1="Ember Attack"
#dict1.sync()
print dict1["Charmander"].var1
#dict1.close()

然而,当我开始使用shelves而不是字典时,当我调用var1时,我得到一个空白。在

^{pr2}$

唯一的区别是我把dict1改成了一本书架词典,而不是一本普通词典。这可能与内存范围或其他东西有关。不管怎样,有人能帮我修改我的代码,让它能和书架一起工作吗?谢谢!在


Tags: selfid字典defshelve词典pokemon书架
1条回答
网友
1楼 · 发布于 2024-05-15 12:23:42
dict1=shelve.open("shelve.dat", writeback=True)

您还可以指定应该提高性能的协议

^{pr2}$

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 (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

相关问题 更多 >