自定义词典通过**kw

And*_*one 3 python

我有一个使用的库函数**kw,但我想传递一个类字典类,以便我可以覆盖它__getitem__来跟踪它对字典中数据的访问.例如,在下面的代码中调用libfn不会打印Accessed但libfn2会打印.

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)
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 5

你不能不改变Python本身.它被转换为dict较低级别.