首页 > 解决方案 > 子类化 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() 吗?那是怎么做的?

标签: pythonpython-3.x

解决方案


因为您没有在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

推荐阅读