0

我决定为个人需求创建一个小跟踪列表。我创建了两个主要类来存储和处理数据。第一个代表主题和练习列表。第二个代表练习列表中的每个练习(主要只是两个变量,所有(完整)答案和正确(好)答案)。

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%

但是当我关闭文件时,下次我打开它时,它会重新启动状态和所有更正丢失。即使用泡菜尝试过,也不起作用。无法弄清楚,为什么它不保存数据。

4

2 回答 2

4

shelve你改变一个对象时,模块不会注意到,只有当你分配它时:

由于 Python 语义,架子无法知道何时修改了可变的持久字典条目。默认情况下,修改的对象仅在分配到架子时才写入。

所以它不承认这sub.exercises[0].modify(18)是一个需要重写回磁盘的操作。

打开数据库时尝试将writeback标志设置为 True。然后它会在关闭时重新保存数据库,即使它没有明确检测到任何更改。

with shelve.open('shelve_classes', writeback=True) as db:
    key = 'Comma splices & Fused sentences'
    sub = db[key]
    sub.exercises[0].modify(18)
    db[key] = sub
于 2016-11-30T13:27:57.267 回答
-3

你不需要关闭数据库吗?喜欢

    db.close()
于 2016-11-30T13:42:31.003 回答