Why doesn't this remove duplicates from my list?
Question:
class MyObject(object):
def __init__(self, no, text):
self.no = no
self.text = text
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text == other.text
return False
def __hash__(self):
return hash(str(self))
my_list = {MyObject(1, 'a'), MyObject(2, 'a'), MyObject(0, 'b')}
print(my_list)
This still prints out 3 objects, but I want to remove one of the elements which has the same ‘a’. Why doesn’t it work? I defined the MyObject class for this de-duplication purpose.
Answers:
You have to either change the hash method’s return value to hash(self.text)
, or, you can keep its return as hash(str(self))
and add a __str__
method whose return value is self.text
.
You didn’t define a __str__
or a __repr__
, and the default repr includes the object’s id.
class MyObject(object):
def __init__(self, no, text):
self.no = no
self.text = text
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text == other.text
return False
def __hash__(self):
return hash(str(self))
my_list = {MyObject(1, 'a'), MyObject(2, 'a'), MyObject(0, 'b')}
print(my_list)
This still prints out 3 objects, but I want to remove one of the elements which has the same ‘a’. Why doesn’t it work? I defined the MyObject class for this de-duplication purpose.
You have to either change the hash method’s return value to hash(self.text)
, or, you can keep its return as hash(str(self))
and add a __str__
method whose return value is self.text
.
You didn’t define a __str__
or a __repr__
, and the default repr includes the object’s id.