Python set([])如何检查两个对象是否相等?对象需要定义哪些方法来自定义此方法?
我需要在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)]) …