Python 向dict添加密钥时调用哪个方法?
我想继承Python 向dict添加密钥时调用哪个方法?,python,dictionary,ordereddictionary,python-collections,Python,Dictionary,Ordereddictionary,Python Collections,我想继承OrderedDict类来设置dict的最大长度 我做到了: from collections import OrderedDict class limitedDict(OrderedDict): def __init__(self, length): OrderedDict.__init__(self) self.length = length 但现在我看不出要覆盖哪个函数来捕获“添加密钥”事件。 我在谷歌上搜索了一会儿,没有找到答案。即使是
OrderedDict
类来设置dict的最大长度
我做到了:
from collections import OrderedDict
class limitedDict(OrderedDict):
def __init__(self, length):
OrderedDict.__init__(self)
self.length = length
但现在我看不出要覆盖哪个函数来捕获“添加密钥”事件。
我在谷歌上搜索了一会儿,没有找到答案。即使是特殊的函数也不能明确回答。使用dunder方法。不过,您需要区分覆盖和设置新键
from collections import OrderedDict
class limitedDict(OrderedDict):
def __init__(self, length):
OrderedDict.__init__(self)
self.length = length
def __setitem__(self, key, value):
if key not in self and len(self) >= self.length:
raise RuntimeWarning("Dictionary has reached maximum size.")
# Or do whatever else you want to do in that case
else:
OrderedDict.__setitem__(self, key, value)
请注意,update
方法也允许添加新钥匙,但它会在引擎盖下调用\uuuu setitem\uuuuu
,如下所示
如果字典超过最大大小,您可能希望
self.popitem(last=False)
直到它与长度匹配(last=False
对于FIFO顺序,last=True
对于后进先出顺序,默认值)。看起来是正确的,谢谢!请注意,您当前的\uuuu init\uuuu
签名不允许将dict初始化为limitedDict(a=2,b=2).
update
最终将调用\uuuu setitem\uuuu
中存在的项,因此它是多余的。其次,update
也适用于iterables,而不仅仅是dicts。@AshwiniChaudhary-True。