Shelve(或pickle)无法正确保存对象的dict。只是松开了d

2024-09-26 18:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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状态和所有更正丢失。即使用泡菜也不行。不明白为什么不保存数据。在


Tags: 文件keynameself列表dbdefsentences
2条回答

你不需要关闭数据库吗?像

    db.close()

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

相关问题 更多 >

    热门问题