我想继承 OrderedDict
类来设置字典的最大长度。
我做到了:
from collections import OrderedDict
class limitedDict(OrderedDict):
def __init__(self, length):
OrderedDict.__init__(self)
self.length = length
但现在我看不到要覆盖哪个函数来捕获“添加 key ”事件。 我谷歌了一段时间没有找到答案。即使是特殊功能也不是明确的答案。
最佳答案
使用 dunder 方法 __setitem__
作为mentioned in the comments通过 @AshwiniChaudhary .不过,您需要区分覆盖和设置新 key 。
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
方法也允许添加新 key ,但它会在后台调用 __setitem__
,如 mentioned in the comments .
如果字典超过最大大小,您可能希望 self.popitem(last=False)
直到它匹配长度(last=False
对于 FIFO 顺序,last=True
后进先出顺序,默认)。
关于python - 向字典添加键时调用哪个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274532/