覆盖Python中的set方法

Cas*_*ash 1 python set python-3.x

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

如果我重写add,remove,__contains__,__str__,update,__iter__,那将是足以使其他操作的行为正确,或者我需要重写什么吗?

Ale*_*lli 7

collections正如@ kaizer.se建议的那样,在抽象类中工作是2.6中的适当解决方案(不确定为什么要调用超级 - 你试图委托哪些功能不能通过包容而不是继承来完成? !).

确实,你没有得到update- 通过提供抽象方法,你得到__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__ __sub__, __xor__, and isdisjoint(来自collections.Set)plus clear, pop, remove, __ior__, __iand__, __ixor__, and __isub__(from collections.MutableSet),这远远超过你从子类化中得到的set(你必须覆盖所有感兴趣的方法) ).你只需要提供你想要的其他设定方法.

请注意,抽象基类collections.Set是来自具体类的非常不同的野兽,包括内置如(set和2.6)旧的sets.Set,已弃用但仍然存在(在Python 3中删除).ABCs意味着继承(并且一旦你实现了所有抽象方法,然后可以合成你的一些方法),其次是"注册"类,因此它们看起来好像从它们继承而且即使它们没有(使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
Run Code Online (Sandbox Code Playgroud)

  • 它可以使用`key(item)`而不是`item.lower()`Anywhere - >`KeySet("Aa",key = operator.methodcaller('lower'))`来推广. (2认同)
  • 为了将来参考,这里有一个基于MutableSet的"KeyedSet"配方.http://code.activestate.com/recipes/576932/ (2认同)