首页 > 解决方案 > 没有 functools total_ordering 的类比较(如 __ge__)

问题描述

以下代码有效,但令人惊讶的是,对于尚未实现的方法也是如此。通常你需要total_ordering来完成这个,对吧?

class Account:

    def __init__(self, balance=0):
        self.balance = balance

    def __lt__(self, other):
        return self.balance < other.balance

    def __le__(self, other):
        return self.balance <= other.balance


acc1 = Account(100)
acc2 = Account(200)

print(acc1 < acc2)   # True
print(acc1 >= acc2)  # False, but __ge__ is not defined
print(acc1 == acc2)  # False, but __eq__ is not defined

不这样做是否安全,total_ordering或者会导致意外?

标签: pythonclassmagic-methods

解决方案


这里发生了两件事。

第一个是==默认情况下总是定义的,继承自object.__eq__. 本质上,它通过身份起作用,这不是您在这里所期望的。

第二个在文档中描述:

这些方法没有交换参数版本(当左参数不支持操作但右参数支持时使用);更确切地说,__lt__()__gt__()是彼此的反映,__le__()并且__ge__()是彼此的反映, __eq__()并且__ne__()是自己的反映。

所以,这就像__add____radd__。在 的情况下acc1 >= acc2,左操作数不支持__gt__,因此将其委托给右操作数的__le__


推荐阅读