Python:集合如何工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2532365/
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
Python: How do sets work
提问by Guy
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are o.id
and o.area
. I want two objects to be equal if these two fields are the same. ie: o1==o2
if and only if o1.area==o2.area and o1.id==o2.id
.
我有一个我想变成一个集合的对象列表。我的对象包含一些字段,其中一些是o.id
和o.area
。如果这两个字段相同,我希望两个对象相等。即:o1==o2
当且仅当o1.area==o2.area and o1.id==o2.id
。
I tried over-writing __eq__
and __cmp__
but I get the error: TypeError: unhashable instance
.
我尝试重写__eq__
,__cmp__
但出现错误:TypeError: unhashable instance
.
What should I over-write?
我应该重写什么?
回答by Marcelo Cantos
Define the __hash__
method to return a meaningful hash based on the id and area fields. E.g.:
定义__hash__
根据 id 和 area 字段返回有意义的散列的方法。例如:
def __hash__(self):
return hash(self.id) ^ hash(self.area)
回答by Yaroslav
"TypeError: unhashable instance." error is probably due to old-style class definition i.e.:
“类型错误:不可散列的实例。” 错误可能是由于旧式的类定义,即:
class A:
pass
Use new style instead:
改用新样式:
class A(object):
pass
If you override __cmp__ function you shouldoverride __hash__ for using your object in sets. In the other case hash considers all object instances as unequal and __cmp__ function will never be called.
如果您覆盖 __cmp__ 函数,您应该覆盖 __hash__ 以在集合中使用您的对象。在另一种情况下,hash 将所有对象实例视为不相等,并且永远不会调用 __cmp__ 函数。