2016-07-19 47 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