good __eq__, __lt__, ..., __hash__ methods for image class?
- by Marten Bauer
I create the following class:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self._hex_digest = hashlib.sha1(self._data).hexDigest()
Images should be equal when all values are equal. Therefore I wrote:
def __eq__(self, other):
if isinstance(other, Image) and self.__dict__ == other.__dict__:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__dict__ < other.__dict__
...
But how should the __hash__ method look like? Equal Images should return equal hashes...
def __hash__(self):
# won't work !?!
return hash(self.__dict__)
Is the way I try to use __eq__, __ne__, __lt__, __hash__, ... recommend?