我需要在Python中创建一个“容器”对象或类,以记录我也定义的其他对象。此容器的一项要求是,如果两个对象被视为相同,则将一个(一个)删除。我的第一个想法是使用aset([])作为包含对象,以完成此要求。
但是,该集合不会删除两个相同的对象实例之一。我必须定义什么才能创建一个?
这是Python代码。
class Item(object):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar
  def __repr__(self):
    return "Item(%s, %s)" % (self.foo, self.bar)
  def __eq__(self, other):
    if isinstance(other, Item):
      return ((self.foo == other.foo) and (self.bar == other.bar))
    else:
      return False
  def __ne__(self, other):
    return (not self.__eq__(other))
口译员
>>> set([Item(1,2), Item(1,2)])
set([Item(1, 2), Item(1, 2)])
显然,__eq__()由x == y调用的不是集合所调用的方法。叫什么 我还必须定义什么其他方法?
注意:Items必须保持可变,并且可以更改,因此我无法提供__hash__()方法。如果这是唯一的方法,那么我将重写以使用不可变Items。