Python 2.6.5 defaultdict覆盖

2024-10-03 09:09:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实现一个字典,它将对插入的键执行某些检查,例如,请参见以下内容:

from collections import defaultdict

class CheckingDict(defaultdict):

    def __init__(self, *args, **kwargs):
        super(CheckingDict, self).__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        if not super(CheckingDict, self).__missing__(key):
            raise ValueError("Key {key} is already present".format(key=key))
        else:
            return defaultdict.__setitem__(self, key, value)

a = CheckingDict(lambda: None)
a[1] = 1

上面代码的问题是它给了我无限递归。所以问题是为什么以及如何正确地做这件事?在

我不想使用组合,因为要获得defaultdict的所有功能,我需要编写更多的代码。在


Tags: key代码fromself字典initvaluedef
1条回答
网友
1楼 · 发布于 2024-10-03 09:09:35

__missing__引起了这个问题,请注意:

  1. 如果__init__只调用超类,那么定义__init__是没有意义的;并且
  2. 实际设置项目时,您没有使用super。在

一个有效的实现:

class CheckingDict(defaultdict):

    def __setitem__(self, key, value):
        if key in self:
            raise ValueError("Key {!r} is already present".format(key))
        super(CheckingDict, self).__setitem__(key, value)

那么为什么调用__missing__调用__setitem__,导致递归呢?该方法不只是告诉您key是否缺少;per the documentation(emphasis mine):

If default_factory is not None, [__missing__] is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

如果键不存在,__missing__实际上是将默认值放入字典中,这意味着它必须调用__setitem__来执行此操作。在

相关问题 更多 >