<p>对于一组完整的比较函数,我使用了以下mixin,您可以将其放入模块中,例如mixin.py。</p>
<pre><code>class ComparableMixin(object):
def _compare(self, other, method):
try:
return method(self._cmpkey(), other._cmpkey())
except (AttributeError, TypeError):
# _cmpkey not implemented, or return different type,
# so I can't compare with "other".
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
</code></pre>
<p>要使用上面的mixin,需要实现一个返回可比较对象键的cmpkey()方法,类似于排序时使用的key()函数。实现可能如下所示:</p>
<pre><code>>>> from .mixin import ComparableMixin
>>> class Orderable(ComparableMixin):
...
... def __init__(self, firstname, lastname):
... self.first = firstname
... self.last = lastname
...
... def _cmpkey(self):
... return (self.last, self.first)
...
... def __repr__(self):
... return "%s %s" % (self.first, self.last)
...
>>> sorted([Orderable('Donald', 'Duck'),
... Orderable('Paul', 'Anka')])
[Paul Anka, Donald Duck]
</code></pre>
<p>我使用这个而不是总的排序方法的原因是<a href="http://bugs.python.org/issue10042" rel="noreferrer">this bug</a>。它在Python3.4中是固定的,但通常也需要支持旧的Python版本。</p>