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
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