我决定为个人需求创建一个小的跟踪列表。 我创建了两个主要的类来存储和处理数据。第一个代表主题和练习列表。第二个代表练习表中的每个练习(主要是两个变量,全部(全部)答案和正确(好)答案)。在
class Subject:
def __init__(self, name):
self.name = name
self.exercises = []
def add(self, exc):
self.exercises.append(exc)
# here is also "estimate" and __str__ methods, but they don't matter
class Exercise:
def __init__(self, good=0, whole=20):
self._good = good
self._whole = whole
def modify(self, good, whole=20):
self._good = good
self._whole = whole
# here is also "estimate" and __str__ methods, but they don't matter
我定义了一个字典,用Subject实例填充它,将其转移到shelve文件并保存。在
^{pr2}$以下是表示(启动状态):
#Comma splices & Fused sentences (0.0%)
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
之后,我试图重新打开转储文件并更新一些值。在
with shelve.open('shelve_classes') as db:
key = 'Comma splices & Fused sentences'
sub = db[key]
sub.exercises[0].modify(18)
db[key] = sub
看起来不错,让我们回顾一下:
print(db[key])
#Comma splices & Fused sentences (18.0%)
#18/20 90.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
但当我关闭文件时,下次打开它时,它会返回到initiate状态和所有更正丢失。即使用泡菜也不行。不明白为什么不保存数据。在
你不需要关闭数据库吗?像
shelve
模块不会注意到您何时对一个对象进行了变异,只有在您分配它时才会注意到:所以它没有意识到
sub.exercises[0].modify(18)
是一个需要重写回磁盘的操作。在打开数据库时尝试将
writeback
标志设置为True。然后它将在关闭时重新保存数据库,即使它没有显式地检测到任何更改。在相关问题 更多 >
编程相关推荐