![]() |
What is the correct way to define __hash__?
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 |
Re: What is the correct way to define __hash__?
On Mon, 12 Oct 2009 15:45:30 -0500, Peng Yu wrote:
> 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)) -- Steven |
Re: What is the correct way to define __hash__?
On Mon, Oct 12, 2009 at 7:04 PM, Steven D'Aprano
<steven@remove.this.cybersource.com.au> wrote: > On Mon, 12 Oct 2009 15:45:30 -0500, Peng Yu wrote: > >> Â* 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)) Assuming you're not using Python 3.x that is. Cheers, Chris -- http://blog.rebertia.com |
Re: What is the correct way to define __hash__?
Chris Rebert wrote:
> On Mon, Oct 12, 2009 at 7:04 PM, Steven D'Aprano > <steven@remove.this.cybersource.com.au> wrote: > >>This can be simplified to: >> >>return cmp((self._a, self._b), (other._a, other._b)) > > Assuming you're not using Python 3.x that is. If you're using Python 3, you won't be writing a __cmp__ method in the first place. -- Greg |
| All times are GMT. The time now is 07:10 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.