如何正确子类化dict并覆盖__getitem__& __setitem__ [英] How to properly subclass dict and override __getitem__ & __setitem__

查看:124
本文介绍了如何正确子类化dict并覆盖__getitem__& __setitem__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一些代码,我想知道什么时候访问一个特定的字典。那么它实际上是一个子类 dict 并实现了一些额外的功能。无论如何,我想做的是子类 dict 我自己,并添加覆盖 __ getitem __ __ setitem__ 产生一些调试输出。现在,我有

  class DictWatch(dict):
def __init __(self,* args):
dict .__ init __(self,args)

def __getitem __(self,key):
val = dict .__ getitem __(self,key)
log.info(GET %s ['%s'] =%s%str(dict.get(self,'name_label')),str(key),str(val)))
return val

def __setitem __(self,key,val):
log.info(SET%s ['%s'] =%s%str(dict.get(self,'name_label' (key),str(val)))
dict .__ setitem __(self,key,val)

' name_label'是一个关键字,最终将被设置为我想用来识别输出。然后,我改变了我正在调用的类,将子类化为 DictWatch 而不是 dict ,并将调用更改为超级构造函数。不过似乎没有发生。我以为我很聪明,但是我想知道我是否应该走一个不同的方向。



感谢您的帮助!

解决方案

你在做什么应该是绝对有效的。我测试了你的课程,除了你的日志语句中的一个缺少的开头圆括号,它的工作正常。我只能想到两件事情。首先,你的log语句的输出是否正确设置?您可能需要在脚本的顶部放置一个 logging.basicConfig(level = logging.DEBUG)



第二, __ getitem __ __ setitem __ [] 访问。因此,请确保您只能通过 d [key] d dictWatch 访问 d.get () d.set()


I am debugging some code and I want to find out when a particular dictionary is accessed. Well, it's actually a class that subclass dict and implements a couple extra features. Anyway, what I would like to do is subclass dict myself and add override __getitem__ and __setitem__ to produce some debugging output. Right now, I have

class DictWatch(dict):
    def __init__(self, *args):
        dict.__init__(self, args)

    def __getitem__(self, key):
        val = dict.__getitem__(self, key)
        log.info("GET %s['%s'] = %s" % str(dict.get(self, 'name_label')), str(key), str(val)))
        return val

    def __setitem__(self, key, val):
        log.info("SET %s['%s'] = %s" % str(dict.get(self, 'name_label')), str(key), str(val)))
        dict.__setitem__(self, key, val)

'name_label' is a key which will eventually be set that I want to use to identify the output. I have then changed the class I am instrumenting to subclass DictWatch instead of dict and changed the call to the superconstructor. Still, nothing seems to be happening. I thought I was being clever, but I wonder if I should be going a different direction.

Thanks for the help!

解决方案

What you're doing should absolutely work. I tested out your class, and aside from a missing opening parenthesis in your log statements, it works just fine. There are only two things I can think of. First, is the output of your log statement set correctly? You might need to put a logging.basicConfig(level=logging.DEBUG) at the top of your script.

Second, __getitem__ and __setitem__ are only called during [] accesses. So make sure you only access DictWatch via d[key], rather than d.get() and d.set()

这篇关于如何正确子类化dict并覆盖__getitem__& __setitem__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆