Links
Notes
From hashable
- An object is hashable if it has a hash value which never
changes during its lifetime (it needs a
__hash__()
method), and can be compared to other objects (it needs an__eq__()
or__cmp__()
method). Hashable objects which compare equal must have the same hash value.
From object.hash(self)
- The only required property is that objects which compare equal have the same hash value
- If a class does not define a
__cmp__()
or__eq__()
method it should not define a__hash__()
operation either - If a class defines mutable objects and implements a
__cmp__()
or__eq__()
method, it should not implement__hash__(),
since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).
Rich Comparisions – functools.total_ordering(cls)
Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:
The class must define one of __lt__()
, __le__()
, __gt__()
,
or __ge__()
. In addition, the class should supply an
__eq__()
method.
For example:
@total_ordering class Student: def __eq__(self, other): return ((self.lastname.lower(), self.firstname.lower()) == (other.lastname.lower(), other.firstname.lower())) def __lt__(self, other): return ((self.lastname.lower(), self.firstname.lower()) < (other.lastname.lower(), other.firstname.lower()))