What is the correct way to define __hash__?

Peng Yu pengyu.ut at gmail.com
Mon Oct 12 22:45:30 CEST 2009


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.


#!/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
      return 0

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

if __name__ == '__main__':

  x = A(1, 1)

  aset = set()
  print aset

More information about the Python-list mailing list