python total_ordering : why __lt__ and __eq__ instead of __le__?

标签 python python-3.x comparison-operators

在 Python3 中,functools.total_ordering decorator允许仅重载 __lt____eq__ 以获得所有 6 个比较运算符。

我不明白为什么一个人必须写两个运算符,一个就足够了,即 __le____ge__,而所有其他运算符都将相应地定义:

a < b   <=>   not (b <= a)
a > b   <=>   not (a <= b)
a == b   <=>   (a <= b) and (b <= a)
a != b   <=>   (a <= b) xor (b <= a)

这仅仅是因为 xor 运算符本身不存在吗?

最佳答案

文档说明您必须定义__lt__() 之一, __le__() , __gt__() , 或 __ge__() ,但只应该提供 __eq__()方法。

换句话说,__eq__方法是可选的

total_ordering implementation不需要您指定 __eq__方法;它只测试 __lt__() , __le__() , __gt__() , 或 __ge__()方法。它基于这 4 种方法中的一种提供最多 3 种缺失的特殊方法。

您不能根据 __le__ 来下订单或 __ge__因为你不能假设你可以交换 ab ;如果b是不同的类型 b.__le__可能没有实现,所以你的 a < b <=> not (b <= a) map 无法保证。实现使用 (a <= b) and (a != b)如果__le__未定义但 __lt__已经。

完整的映射表是:

<表类="s-表"> <头> 比较 可用 选择 <正文> a > b a < b (not a < b) and (a != b) a <= b (not a <= b) a >= b (a >= b) and (a != b) a <= b a < b (a < b) or (a == b) a > b (not a > b) a >= b (not a >= b) or (a == b) a < b a <= b (a <= b) and (a != b) a > b (not a > b) and (a != b) a >= b (not a >= b) a >= b a < b (not a < b) a <= b (not a <= b) or (a == b) a > b (a > b) or (a == b)

__eq__方法是可选的,因为基础 object object 为你定义了一个;只有当两个实例是同一个对象时,它们才被认为是相等的; ob1 == ob2仅当ob1 is ob2True .查看 do_richcompare() function in object.c ;请记住 ==代码中的运算符有比较指针。

关于 python total_ordering : why __lt__ and __eq__ instead of __le__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238322/

相关文章:

python - 算法与复杂性书籍

scala - Scala 中的符号 =?= 是什么意思?

java equal 和 == 混淆

python - KeyboardInterrupt 在不同的执行中表现不同

ruby - Array#-(减法运算符)如何比较元素是否相等?

python - 如何有效地找到与第二个数组值匹配的第一个数组值的索引?

python - 有没有办法在 pytest 中嵌套 fixture 参数化?

python - 获取深度自动编码器的解码器

python - 对给定行 pandas 的跨列求和分类特征标签

python-3.x - 包括 Python 包内的文件夹和文件