2016-07-19 46 views
0

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

例如:

import __builtin__ 

def test(a): 
    print a 

__builtin__.update = test 

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

我的意思:

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

我想显示出下面的文本打印: “关键” 和 “价值”

亲切的问候, 丹尼斯

回答

0
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) 
+0

有没有一种方法,我可以不用一类? – Denis

+0

字典已经是一个类,所以你已经在使用一个类...但是,不,你可能不会说'dict.update = some_other_func',因为我确定你知道(因为你可能已经在你的示例代码中尝试过了......) (这不完全是真的...更新答案) –

+0

感谢它的工作 – Denis

0

您可以通过继承子类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}) 
+0

我真的不想使用一个类。是否有一种方法,我可以没有它呢? – Denis