使用 Python 处理类字典
对于这个例子,我有一本字典,当我调用它时,会显示“Ember Attack”。
#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()
然而,当我开始使用书架而不是字典时,当我调用 var1 时,我得到一个空白。
import shelve
class Pokemon():
"""Each patient'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()
唯一的区别是我将 dict1 设为搁置字典而不是常规字典。它可能与内存范围或其他东西有关。无论如何,有人可以帮我修改我的代码,以便它可以与货架一起使用吗?谢谢!
For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed.
#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()
However when I start using shelves instead of the dictionary, I get a blank when I call on var1.
import shelve
class Pokemon():
"""Each patient'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()
The only difference is that I made dict1 a shelve dictionary instead of a regular dictionary. It probably has to do with memory scope or something. Anyway, can someone help me revise my code so that it will work with shelves? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还可以指定应该提高性能的协议
you can also specify the protocol which should improve performance