重写 Python 中的 set 方法

2023-12-08

我想创建一个自定义集,它将自动将对象转换为不同的形式以存储在集中(请参阅使用Python字典作为非嵌套的键)作为背景。

如果我覆盖add, remove, __contains__, __str__, update, __iter__,这足以使其他操作正常运行,还是我需要覆盖其他任何操作?


工作自collections的抽象类,正如 @kaizer.se 所建议的,是 2.6 中合适的解决方案(不确定为什么你想调用 super ——你试图委托什么功能,而这些功能不能通过包含而不是继承来最好地完成?!) 。

确实你不明白update-- 通过提供抽象方法,你确实得到了__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__ __sub__, __xor__, and isdisjoint (from collections.Set) plus clear, pop, remove, __ior__, __iand__, __ixor__, and __isub__ (from collections.MutableSet),这远远超过你从子类化中得到的set(你必须重写every兴趣方法)。您只需提供您想要的其他设置方法即可。

请注意,抽象基类如collections.Set是与具体类完全不同的野兽,包括诸如set和(2.6)好老sets.Set,已弃用但仍然存在(在 Python 3 中删除)。 ABC 旨在继承(并且一旦您实现了所有抽象方法,就可以从您那里合成一些方法,正如您必须的那样),其次是“注册”类,这样它们看起来就像是从它们继承的,即使它们没有继承(使isinstance更可用和有用)。

这是 Python 3.1 和 2.6 的工作示例(没有充分的理由使用 3.0,因为 3.1 只比它有优点,没有缺点):

import collections

class LowercasingSet(collections.MutableSet):
  def __init__(self, initvalue=()):
    self._theset = set()
    for x in initvalue: self.add(x)
  def add(self, item):
    self._theset.add(item.lower())
  def discard(self, item):
    self._theset.discard(item.lower())
  def __iter__(self):
    return iter(self._theset)
  def __len__(self):
    return len(self._theset)
  def __contains__(self, item):
    try:
      return item.lower() in self._theset
    except AttributeError:
      return False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重写 Python 中的 set 方法 的相关文章

随机推荐