正如@kaizer.se 所建议的,使用collections 的抽象类是2.6 中的合适解决方案(不知道为什么要调用super——你试图委派哪些功能不能最好地完成通过遏制而不是继承?!)。
确实,你没有得到update——通过提供抽象方法,你得到了__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__ __sub__, __xor__, and isdisjoint(来自collections.Set)加上clear, pop, remove, __ior__, __iand__, __ixor__, and __isub__(来自collections.MutableSet),这远远超过您将从子类化 set 中获得(您必须覆盖 每个 感兴趣的方法)。您只需要提供您想要的其他设置方法。
请注意,像 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