python - 如何检测 Python 中嵌套对象的修改?

标签 python object magic-methods

假设我有这样的东西(未测试):

class Foo(object):
    def __init__(self):
        self.store = {}

    def __setitem__(self, key, value):
        self.store[key] = value
        print('Detected set')

    def __getitem__(self, key):
        return self.store[key]

__setitem__ 仅在对象本身更改时调用:

 foo = Foo()
 foo['bar'] = 'baz'

但它不会被调用,例如,当:

 foo['bar'] = {}
 foo['bar']['baz'] = 'not detected inside dict'

我怎样才能检测到这种情况,或者我应该用其他什么方法来检测这种情况?我的目标是拥有一个类似于字典的对象,它始终与磁盘上的文件同步。

最佳答案

我建议使用 shelve。我提供了一个持久性字典。 使用 writeback=True 打开文件会强制与文件同步:

db = shelve.open('test.db', writeback=True)

把它当作字典:

>>> db['a'] = {}
>>> db['a']['x'] = 10
>>> dict(db)
{'a': {'x': 10}}

关闭重新打开:

>>> db.close()
>>> db = shelve.open('test.db', writeback=True)
>>> dict(db)
{'a': {'x': 10}}

数据还在。

关于python - 如何检测 Python 中嵌套对象的修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217410/

相关文章:

python - Python中是否可以在子进程和主进程之间分离CPU资源?

python - 如何并行并发 HTTP 请求

javascript - 测试嵌套 JavaScript 对象键是否存在

JavaScript:根据条件创建二维对象数组

PHP - 一直调用

python - django value_list 给出 id 而不是值

python - 如何显示我的 Jupyter 笔记本的版本并在 Jupyter 笔记本中运行单元格?我收到错误 : bad interpreter

javascript - React - 模块解析失败 : Unexpected token

python - python del 语句的神奇方法?

php - 是否有可能使用 PHPUnit 模拟对象来调用神奇的 __call() 方法?