我想实现一个字典,它将对插入的键执行某些检查,例如,请参见以下内容:
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
的所有功能,我需要编写更多的代码。在
是
__missing__
引起了这个问题,请注意:__init__
只调用超类,那么定义__init__
是没有意义的;并且super
。在一个有效的实现:
那么为什么调用
__missing__
调用__setitem__
,导致递归呢?该方法不只是告诉您key
是否缺少;per the documentation(emphasis mine):如果键不存在,
__missing__
实际上是将默认值放入字典中,这意味着它必须调用__setitem__
来执行此操作。在相关问题 更多 >
编程相关推荐