In python - the operator which a set uses for test if an object is in the set
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 In Python - The Operator Which A Set Uses For Test If An Object Is In The Set
00:44 Accepted Answer Score 9
01:02 Thank you
--
Full question
https://stackoverflow.com/questions/8675...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #object #set #overriding
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 In Python - The Operator Which A Set Uses For Test If An Object Is In The Set
00:44 Accepted Answer Score 9
01:02 Thank you
--
Full question
https://stackoverflow.com/questions/8675...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #object #set #overriding
#avk47
ACCEPTED ANSWER
Score 9
set uses __hash__ for comparison. Override that, and you'll be good:
class MyClass(object):
def __init__(self, s):
self.s = s
def __cmp__(self, other):
return cmp(self.s, other.s)
def __hash__(self):
return hash(self.s) # Use default hash for 'self.s'
instance1, instance2 = MyClass("a"), MyClass("a")
instance3 = MyClass("b")
print instance2==instance1 # True
print instance2 in [instance1] # True
print instance2 in set([instance1]) # True