【问题标题】:Create a custom deque class without appendleft method, inheriting from collections.deque [duplicate]创建一个没有 appendleft 方法的自定义 deque 类,继承自 collections.deque [重复]
【发布时间】:2021-10-21 03:37:59
【问题描述】:

我只想在我的自定义双端队列类中有 append 方法。

我试过这个:

from collections import deque

del deque.appendleft

class CustomDeque(deque):
     pass

但我收到以下错误:

----> 3 del deque.appendleft
      4
      5 class CustomDeque(deque):

TypeError: can't set attributes of built-in/extension type 'collections.deque'

我想得到这种行为:

>>> custom_deque = CustomDeque()

>>> custom_deque.appendleft()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

----> 1 custom_deque.appendleft()

AttributeError: 'CustomDeque' object has no attribute 'appendleft'

【问题讨论】:

  • 为什么不直接使用现有的deque 类而不使用 appendleft 方法?
  • @mkrieger1 我觉得最好不要让程序员有可能去做,我们是人,会犯错。

标签: python oop inheritance


【解决方案1】:

一个选项(有一个不同的,可能更合适的错误):

from collections import deque

class CustomDeque(deque):
    def appendleft(self, item):
        raise NotImplementedError

当然,您也可以引发AttributeError,但这只会在实际调用该方法时引发。如果您真的想隐藏该属性,则必须覆盖__getattribute__

class CustomDeque(deque):
    def __getattribute__(self, name):
        if name == "appendleft":
            raise AttributeError
        return super().__getattribute__(name)

现在,纯属性查找和尝试的函数调用都会引发错误:

>>> c = CustomDeque()
>>> c.appendleft
# ...
AttributeError

>>> c.appendleft()
# ...
AttributeError

>>> hasattr(c, "appendleft")
False

但是请注意,仍然可以通过以下方式追加到左侧:

c.insert(0, ...)

【讨论】:

  • 谢谢!这是一个假设情况,在这种情况下,我将禁用所有相关方法以仅将其用作 FIFO 或 LIFO。因为我们在 Python 中没有严格的 FIFO/LIFO 内置实现
  • 让你的自定义类不继承自双端队列可能更容易,而是将其用作一些受保护的属性,然后添加你想要的方法。白名单似乎比黑名单更透明;)
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 2021-08-23
  • 2022-11-09
  • 2020-10-21
  • 2019-12-30
  • 2018-10-14
相关资源
最近更新 更多