python - 子类化 collections.abc.MutableMapping - 更新方法
问题描述
我试图理解collections.abc.MutableMapping
. 我创建了自己的版本dict
,打印了一些信息:
from collections.abc import MutableMapping
class MutableMappingTest(MutableMapping):
def __init__(self, *args, **kwargs):
print('__init__', args, kwargs)
self.my_store = dict()
self.update(dict(*args, **kwargs))
def __getitem__(self, key):
print('__getitem__:', key)
return self.my_store[key]
def __setitem__(self, key, value):
print('__setitem__:', key, value)
self.my_store[key] = value
def __delitem__(self, key):
print('__delitem__:', key)
del self.my_store[key]
def __iter__(self):
print('__iter__')
return iter(self.my_store)
def __len__(self):
print('__len__')
return len(self.my_store)
我不明白的是:当我通过分配给嵌套属性进行更新时,__setitem__
不会调用,只是__getitem__
:
>>> t = MutableMappingTest(test={"deep": "foo"})
__init__ () {'test': {'deep': 'foo'}}
__setitem__: test {'deep': 'foo'}
>>> t['test']['deep'] = 'bar'
__getitem__: test
我如何还可以更新嵌套属性。我必须覆盖 update() 吗?那是怎么做的?
解决方案
因为您没有在t
. 相反,您从 获取常规字典t
,然后在该字典中设置一个项目。
如果您希望子字典表现得像MutableMappingTest
对象,则必须使它们成为MutableMappingTest
对象。
>>> t = MutableMappingTest(test=MutableMappingTest(deep="foo"))
__init__ () {'deep': 'foo'}
__setitem__: deep foo
__init__ () {'test': <__main__.MutableMappingTest object at 0x000001EA3C1DDB00>}
__setitem__: test <__main__.MutableMappingTest object at 0x000001EA3C1DDB00>
>>> t['test']['deep'] = 'bar'
__getitem__: test
__setitem__: deep bar
推荐阅读
- vue.js - nuxtjs 默认阻止加载 youtube 视频还是浏览器?
- flutter - Flutter:何时使用`print`和`debugPrint`?
- dart - 无法访问 Dart 库中的私有方法
- c# - 我收到 AuthorizationsDenied 错误
- eclipse - 自定义继承 Xtext 的范围
- iis - 电子自动更新
- android - android studio 上的颜色与物理设备上的颜色不同
- google-apps-script - CSV 处理并上传到 Google Analytics
- python - 想用脚本python从json文件中删除方括号
- apache-kafka - 在 Kafka 和镜像制造商之间传输数据的最佳压缩格式或技术是什么?