搁置(或泡菜)不能正确保存对象的字典。它只是丢失了数据

Shelve (or pickle) doesn't save the dict of objects correctly. It just looses the data

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

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%

但是当我关闭文件,下次打开它时,它又回到启动状态和所有更正丢失。即使用泡菜试过,也不起作用。想不通,为什么不保存数据。

shelve 模块不会在您改变对象时注意到,只有在您分配它时才会注意到:

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.

所以它不识别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

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

    db.close()