我决定为个人需求创建一个小跟踪列表。我创建了两个主要类来存储和处理数据。第一个代表主题和练习列表。第二个代表练习列表中的每个练习(主要只是两个变量,所有(完整)答案和正确(好)答案)。
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 实例填充它,将它转移到搁置文件并保存。
with shelve.open("shelve_classes") as db:
db.update(initiate())
这是表示(初始状态):
#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%
但是当我关闭文件时,下次我打开它时,它会重新启动状态和所有更正丢失。即使用泡菜尝试过,也不起作用。无法弄清楚,为什么它不保存数据。