当它被传递给另一个字典的更新方法时,拦截dict __getitem__方法调用

时间:2012-09-27 06:36:13

标签: python dictionary

如您所知,python允许我们简单地覆盖dict.__getitem__方法,这样当有人试图从中检索任何值时,我们可以在那里做一些不同的事情。

我想在传递一个MyDict(dict)类实例来更新另一个python dict实例的方法时做一些代码。见下文:

class MyDict(dict):
    def __getitem__(self, item):
        print "Doing some stuff here"
        return dict.__getitem__(self, item)

d1 = MyDict({'1': 1, '2': 2})
d2 = {}
# I want to have d1.__getitem__ called, but it does not work :-(
d2.update(d1)

2 个答案:

答案 0 :(得分:1)

尝试使用collections.Mapping abstract base class(或collections.MutableMapping,如果这是读写的话)。

import collections

class MyDict(collections.Mapping):
    def __init__(self, *args, **kwargs):
        self.data = dict(*args, **kwargs)

    def __len__(self):
        return len(self.data)

    def __iter__(self):
        return iter(self.data)

    def __contains__(self, key):
        return key in self.data

    def __getitem__(self, key):
        print 'Doing some stuff here'
        return self.data[key]

答案 1 :(得分:0)

您只需要从MyDict继承object并为其创建.keys()方法。见下文:

class MyDict(object):
    def __init__(self, items=()):
        self._dict = dict(items)

    def keys(self):
        return self._dict.keys()

    def __getitem__(self, item):
        print "Doing some stuff for item:", item
        return self._dict[item]

    def __setitem__(self, item, value):
        self._dict[item] = value

    # You can add some more dict methods

d1 = MyDict({'1': 1, '2': 2})
d2 = {}
# Now you will see some stuff executed for each
# value extracted from d1 while updating d2
d2.update(d1)