3 回答

TA贡献1887条经验 获得超5个赞
您正在做的事情绝对应该有效。我测试了您的类,除了在日志语句中缺少左括号之外,它还可以正常工作。我只能想到两件事。首先,您的log语句的输出设置正确吗?您可能需要logging.basicConfig(level=logging.DEBUG)在脚本的顶部放置一个。
其次,__getitem__和__setitem__只在所谓的[]访问。因此,请确保您仅DictWatch通过d[key]而不是d.get()和访问d.set()

TA贡献1805条经验 获得超9个赞
子类化时的另一个问题dict是,内置__init__函数不会调用update,而内置update函数不会调用__setitem__。因此,如果您希望所有setitem操作都通过您的__setitem__函数,则应确保自己调用该函数:
class DictWatch(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __getitem__(self, key):
val = dict.__getitem__(self, key)
print 'GET', key
return val
def __setitem__(self, key, val):
print 'SET', key, val
dict.__setitem__(self, key, val)
def __repr__(self):
dictrepr = dict.__repr__(self)
return '%s(%s)' % (type(self).__name__, dictrepr)
def update(self, *args, **kwargs):
print 'update', args, kwargs
for k, v in dict(*args, **kwargs).iteritems():
self[k] = v

TA贡献1815条经验 获得超13个赞
那并不能真正改变结果(对于良好的日志记录阈值,它应该可以工作):您的init应该是:
def __init__(self,*args,**kwargs) : dict.__init__(self,*args,**kwargs)
相反,因为如果使用DictWatch([(1,2 ,,(2,3)])或DictWatch(a = 1,b = 2)调用方法,则此操作将失败。
(或者,最好不要为此定义一个构造函数)
添加回答
举报