Python set([]) 如何检查两个对象是否相等?对象需要定义哪些方法来自定义它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3942303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?
提问by Ada
I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a set([])as the containing object, to complete this requirement.
我需要在 Python 中创建一个“容器”对象或类,它保留我也定义的其他对象的记录。该容器的一个要求是,如果两个对象被认为是相同的,则删除一个(其中一个)。我的第一个想法是使用 aset([])作为包含对象,以完成此要求。
However, the set does not remove one of the two identical object instances. What must I define to create one?
但是,该集合不会删除两个相同的对象实例之一。我必须定义什么才能创建一个?
Here is the Python code.
这是 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))
Interpreter
口译员
>>> set([Item(1,2), Item(1,2)])
set([Item(1, 2), Item(1, 2)])
It is clear that __eq__(), which is called by x == y, is not the method called by the set. What is called? What other method must I define?
很明显__eq__(),被 调用的x == y不是集合调用的方法。什么叫?我还必须定义什么其他方法?
Note: The Items must remain mutable, and can change, so I cannot provide a __hash__()method. If this is the only way of doing it, then I will rewrite for use of immutable Items.
注意:Items 必须保持可变,并且可以更改,因此我无法提供__hash__()方法。如果这是唯一的方法,那么我将重写以使用 immutable Items。
采纳答案by eumiro
I am afraid you will have to provide a __hash__()method. But you can code it the way, that it does not depend on the mutable attributes of your Item.
恐怕您将不得不提供一种__hash__()方法。但是您可以按照这种方式对其进行编码,即它不依赖于Item.
回答by ruena
Yes, you need a __hash__()-method AND the comparing-operator which you already provided.
是的,您需要一个__hash__()-method 和您已经提供的比较运算符。
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))
def __hash__(self):
return hash(self.__repr__())

