除非其他人通过找到更好的解决方案来提供帮助,否则我会这样做:
# to get __hash__ and __eq__ return id(self)
class Reference:
def __init__(self, item):
self.item = item
class RemovalAPI:
def add_removal_info(self, item, removal_info):
try:
references = item.__reference
except AttributeError:
references = item.__reference = {}
references[Reference(self)] = removal_info
def get_removal_info(self, item):
try:
references = item.__reference
self_reference = Reference(self)
return references[self_reference]
class Container(list, RemovalAPI):
def __iter__(self):
for i in range(len(self)):
item = self[i]
self.add_removal_info(item, i)
yield item
def remove(self, item):
removal_info = self.get_removal_info(item)
del self[removal_info]
def insert(self, item):
self.add_removal_info(item, len(self))
self.append(item)
# do whatever post-processing I need
# ...
如果我决定将实现从list
其他数据结构更改,公共接口可以保持不变:
class Container(orderedset, RemovalAPI):
# inheriting __iter__, remove from parent
def insert(self, item):
self.add(item)
# do whatever post-processing I need
# ...
或者...
class Container(linkedlist, RemovalAPI):
def __iter__(self):
it = super().__iter__()
last_item = None
for item in it:
self.add_removal_info(item, last_item)
yield item
def remove(self, item):
removal_info = self.get_removal_info(item)
if removal_info is None:
self.remove_first()
else:
self.remove_after(removal_info)
def insert(self, item):
self.add_removal_info(item, None)
self.add_to_front(item)
# do whatever post-processing I need
# ...