good __eq__, __lt__, ..., __hash__ methods for image class?

Posted by Marten Bauer on Stack Overflow See other posts from Stack Overflow or by Marten Bauer
Published on 2010-03-31T18:10:41Z Indexed on 2010/03/31 18:13 UTC
Read the original article Hit count: 357

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about pythonic