VPf*_*PfB 10 python dictionary
我已经分类dict并且需要检测它的所有修改.
(我知道我无法检测到存储值的就地修改.没关系.)
我的代码:
def __setitem__(self, key, value):
super().__setitem__(key, value)
self.modified = True
def __delitem__(self, key):
super().__delitem__(key)
self.modified = True
Run Code Online (Sandbox Code Playgroud)
问题是它只适用于简单的分配或删除.它未检测到所做的更改pop(),popitem(),clear()和update().
为什么__setitem__和__delitem__当项目被添加或删除绕过?我是否还必须重新定义所有这些方法(pop等等)?
对于这种用法,您不应该继承dictclass,而是使用collectionsPython标准库模块的抽象类.
您应该对MutableMapping抽象类进行子类化并覆盖以下方法:__getitem__,__setitem__和__delitem__,__iter__以及__len__使用内部字典的所有方法.抽象基类确保所有其他方法都将使用这些方法.
class MyDict(collections.MutableMapping):
def __init__(self):
self.d = {}
# other initializations ...
def __setitem__(self, key, value):
self.d[key] = value
self.modified = true
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
304 次 |
| 最近记录: |