4

如您所知,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)
4

2 回答 2

1

尝试使用抽象基类(或者,如果这是读写)。collections.Mapping 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]
于 2012-09-27T07:04:20.843 回答
0

您所需要的只是从中继承MyDictobject为其创建.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)
于 2012-09-27T19:08:09.490 回答