What is the correct way to define __hash__?

Peng Yu pengyu.ut at gmail.com
Mon Oct 12 16:56:41 EDT 2009


On Mon, Oct 12, 2009 at 3:45 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
> 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.
>
> Regards,
> Peng
>
>
> #!/usr/bin/env python
>
> class A:
>  def __init__(self, a, b) :
>    self._a = a
>    self._b = b
>
>  def __str__(self):
>    return 'A(%s, %s)' %(self._a, self._b)
>
>  __repr__ = __str__
>
>  def __cmp__(self, other):
>    if self._a < other._a:
>      return -1
>    elif self._a > other._a:
>      return 1
>    elif self._b < other._b:
>      return -1
>    elif self._b > other._b:
>      return 1
>    else:
>      return 0
>
>  def __hash__(self):
>    return self._a + self._b
>
> if __name__ == '__main__':
>
>  x = A(1, 1)
>
>  aset = set()
>  aset.add(x)
>  print aset


What if A has a third member, which is a string? Is there a function
to convert an arbitrary string to an int?



More information about the Python-list mailing list