我有一個庫函數,它使用**kw
,但我想傳遞一個類似字典的類,以便我可以覆蓋__getitem__
來跟蹤對字典中對數據的訪問。例如,在下面的代碼中調用libfn不會打印訪問但libfn2會。自定義字典通過** kw
class Dtracker(dict):
def __init__(self):
dict.__init__(self)
def __getitem__(self,item):
print "Accessed %s" % str(item)
return dict.__getitem__(self, item)
def libfn(**kw):
a = kw["foo"]
print "a is %s" % a
return a
def libfn2(kw):
a = kw["foo"]
print "a is %s" % a
return a
d = Dtracker()
d["foo"] = "bar"
libfn(**d)
libfn2(d)
謝謝!雖然第一個回答「你不能」似乎在技術上是正確的,但是這個回答讓我想要以最少的變化去做 - 最重要的是沒有API變化。我只需要破解圖書館*嘆息*。 – AndrewStone
「破解圖書館」? –