On 11/6/05, John Williams <jrw at pobox.com> wrote: > (This is kind of on a tangent to the original discussion, but I don't > want to create yet another subject line about object comparisons.) > > Lately I've found that virtually all my implementations of __cmp__, > __hash__, etc. can be factored into this form inspired by the "key" > parameter to the built-in sorting functions: > > class MyClass: > > def __key(self): > # Return a tuple of attributes to compare. > return (self.foo, self.bar, ...) > > def __cmp__(self, that): > return cmp(self.__key(), that.__key()) > > def __hash__(self): > return hash(self.__key()) The main way this breaks down is when comparing objects of different types. While most comparisons typically are defined in terms of comparisons on simpler or contained objects, two objects of different types that happen to have the same "key" shouldn't necessarily be considered equal. -- --Guido van Rossum (home page: http://www.python.org/~guido/)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4