Python: How do sets work

醉酒当歌 提交于 2020-01-22 10:28:08

问题


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.

I tried over-writing __eq__ and __cmp__ but I get the error: TypeError: unhashable instance.

What should I over-write?


回答1:


Define the __hash__ method to return a meaningful hash based on the id and area fields. E.g.:

def __hash__(self):
    return hash(self.id) ^ hash(self.area)



回答2:


"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 should override __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.



来源:https://stackoverflow.com/questions/2532365/python-how-do-sets-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!