python - 向字典添加键时调用哪个方法?

标签 python dictionary ordereddictionary python-collections

我想继承 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/

相关文章:

python - 具有无限循环和队列的基本多处理

javascript - 当一个简单的 For Loop 工作正常时,我的 forEach 方法有什么问题

powershell - foreach($map.keys 中的 $key)的行为不符合预期

json - python json中的ordered_dict

python字典键与对象属性

python - 从 ordereddict 生成 Pandas 数据框?

python - 步长的原因是什么?

python - 什么是沙漏导入,为什么要在代码库中避免它们?

python - 使用 boto 在 amazon mechanical turk 中将 HIT 分组?

python - Dictionary子类,所有的编辑方法都被回调覆盖了吗?