How do sets work in Python?

0 votes
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 following error:

TypeError: unhashable instance.

Please tell me what should I over-write?
Apr 12 in Python by ana1504.k
• 5,910 points
9 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
Define the __hash__ method to return a meaningful hash based on the id and area fields.

For example, you can try this:

def __hash__(self):
    return hash(self.id) ^ hash(self.area)
answered Apr 12 by SDeb
• 9,380 points

Related Questions In Python

0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27 in Python by rajesh
• 1,210 points
17 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by ariaholic
• 7,320 points
773 views
0 votes
1 answer

How do I copy a file in python?

Use the shutil module. copyfile(src, dst) Copy the contents ...READ MORE

answered Jul 31, 2018 in Python by Priyaj
• 56,100 points
23 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 56,100 points
99 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
19 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 9,380 points
61 views
0 votes
1 answer

How does % work in Python?

The % (modulo) operator yields the remainder ...READ MORE

answered Oct 10, 2018 in Python by SDeb
• 9,380 points
12 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.