缓慢但优雅的方法是创建一个具有相反顺序的值包装器:
from functools import total_ordering@total_orderingclass ReversedOrder: def __init__(self, value): self.value = value def __eq__(self, other): return other.value == self.value def __lt__(self, other): return other.value < self.value
如果没有
functools.total_ordering,则必须实施所有6个比较,例如:
import operatorclass ReversedOrder: def __init__(self, value): self.value = valuefor x in ['__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__']: op = getattr(operator, x) setattr(ReversedOrder, x, lambda self, other, op=op: op(other.value, self.value))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)