【问题标题】:Which method is called when adding a key to a dict?向字典添加键时调用哪个方法?
【发布时间】:2018-03-14 09:54:01
【问题描述】:

我想继承OrderedDict 类来设置字典的最大长度。

我做到了:

from collections import OrderedDict

class limitedDict(OrderedDict):
    def __init__(self, length):
        OrderedDict.__init__(self)
        self.length = length

但现在我看不到要覆盖哪个函数来捕获“添加键”事件。 我谷歌了一段时间没有找到答案。即使是特殊功能也不是一个明确的答案。

【问题讨论】:

标签: python dictionary ordereddictionary python-collections


【解决方案1】:

使用 dunder 方法 __setitem__ 作为 mentioned in the comments by @AshwiniChaudhary。不过,您需要区分覆盖和设置新密钥。

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 方法也允许添加新密钥,但它在后台调用__setitem__,如mentioned in the comments

如果字典超过了您可能希望self.popitem(last=False) 的最大大小,直到它与长度匹配(last=False 用于 FIFO 顺序,last=True 用于 LIFO 顺序,默认值)。

【讨论】:

  • update 最终将调用__setitem__ 来获取other 中存在的项目,因此它是多余的。其次,update 也适用于可迭代对象,而不仅仅是字典。
  • @AshwiniChaudhary True.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-25
  • 1970-01-01
  • 2015-08-24
  • 2010-11-04
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多