What is the correct way to define __hash__?

P

Peng Yu

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
 
S

Steven D'Aprano

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

This can be simplified to:

return cmp((self._a, self._b), (other._a, other._b))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top