Python中的可比较类3 [英] Comparable classes in Python 3
问题描述
在Python 3中使类可比的标准方法是什么? (例如,通过id。)
What is the standard way of making a class comparable in Python 3? (For example, by id.)
推荐答案
对于一整套比较函数,我使用了下面的mixin,你可以
For a full set of comparison functions I have used the following mixin, which you could put in say for example a mixin.py in your module.
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)
要使用上面的mixin,你需要实现一个_cmpkey()方法,返回一个可以比较的对象的键,类似于排序时使用的key()函数。实施方式如下:
To use the mixin above you need to implement a _cmpkey() method that returns a key of objects that can be compared, similar to the key() function used when sorting. The implementation could look like this:
>>> 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]
我使用这个而不是total_ordering配方的原因是此错误。它在Python 3.4中是固定的,但通常你还需要支持旧的Python版本。
The reason I use this instead of the total_ordering recipe is this bug. It's fixed in Python 3.4, but often you need to support older Python versions as well.
这篇关于Python中的可比较类3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!