On 11/6/05, John Williams <[EMAIL PROTECTED]> 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/)
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to