What is the correct way to define __hash__?

Christian Heimes lists at cheimes.de
Mon Oct 12 17:10:54 EDT 2009


Peng Yu schrieb:
> Hi,
> 
> I'm wondering what is the general way to define __hash__. I could add
> up all the members. But I am wondering if this would cause a
> performance issue for certain classes.


>   def __hash__(self):
>     return self._a + self._b


The hash of a tuple is based on the hash of its values. A common way to
define a hash method is:

    def __hash__(self):
        return hash((self._a, self._b))

Christian




More information about the Python-list mailing list