修改字典的 .update 函数

Modify .update function for dictionary

我想知道如何从 dict 修改已经存在的 .update 函数。

例如:

import __builtin__

def test(a):
    print a

__builtin__.update = test

所以当我再次使用 X.update 时,它会显示一个打印的值。

我的意思是:

test = {}
test.update({ "Key" : "Value" })

我想要显示以下文本的印刷品:"Key" 和 "Value"

亲切的问候, 丹尼斯

class dict2(dict):
    def update(*args,**kwargs):
        print "Update:",args,kwargs
        dict.update(*args,**kwargs)

d = dict2(a=5,b=6,c=7)
d.update({'x':10})

我确定你注意到你不能简单地做 dict.update=some_other_fn ......但是,如果你既有决心又足够鲁莽,有很多方法可以做到......

~> sudo pip install forbiddenfruit
~> python
...
>>> from forbiddenfruit import curse
>>> def new_update(*args,**kwargs): 
       print "doing something different..."
>>> curse(dict,"update",new_update)

您可以通过子类化 dict 来覆盖更新方法。

from collections import Mapping 

class MyDict(dict):
    def update(self, other=None, **kwargs):
        if isinstance(other, Mapping):
            for k, v in other.items():
                print(k, v)
            super().update(other, **kwargs)

m = MyDict({1:2})
m.update({2:3})