can a class instance ever be hashable?

Alex cut_me_out at hotmail.com
Thu Sep 21 20:56:40 EDT 2000


Read about these methods in the Language Reference documentation.  Any
class that defines them can be hashable.  In fact you only need to
define __hash__, but that will lead to confusing results when you have
different instances that you want to regard as equal for some reason.

__cmp__ (self, other)
    Called by all comparison operations. Should return a negative
    integer if self < other, zero if self == other, a positive integer
    if self > other. If no __cmp__() operation is defined, class
    instances are compared by object identity (``address''). (Note: the
    restriction that exceptions are not propagated by __cmp__() has been
    removed in Python 1.5.)

__hash__ (self)
    Called for the key object for dictionary operations, and by the
    built-in function hash(). Should return a 32-bit integer usable as a
    hash value for dictionary operations. The only required property is
    that objects which compare equal have the same hash value; it is
    advised to somehow mix together (e.g., using exclusive or) the hash
    values for the components of the object that also play a part in
    comparison of objects. If a class does not define a __cmp__() method
    it should not define a __hash__() operation either; if it defines
    __cmp__() but not __hash__() its instances will not be usable as
    dictionary keys. If a class defines mutable objects and implements a
    __cmp__() method it should not implement __hash__(), since the
    dictionary implementation requires that a key's hash value is
    immutable (if the object's hash value changes, it will be in the
    wrong hash bucket).

-- 
Speak softly but carry a big carrot.



More information about the Python-list mailing list