python - 没有 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
或者会导致意外?
解决方案
这里发生了两件事。
第一个是==
默认情况下总是定义的,继承自object.__eq__
. 本质上,它通过身份起作用,这不是您在这里所期望的。
第二个在文档中描述:
这些方法没有交换参数版本(当左参数不支持操作但右参数支持时使用);更确切地说,
__lt__()
和__gt__()
是彼此的反映,__le__()
并且__ge__()
是彼此的反映,__eq__()
并且__ne__()
是自己的反映。
所以,这就像__add__
和__radd__
。在 的情况下acc1 >= acc2
,左操作数不支持__gt__
,因此将其委托给右操作数的__le__
。
推荐阅读
- r - R:加速包含哪个循环的循环
- excel - VBA 运行时错误 '1004' ~ Sum if Function with variable sheet name in function
- proxy - 通过 pip3 安装时遇到问题
- android - Square SDK 无法通过蓝牙配对阅读器
- python - Accuracy for Regression
- excel - 如何将我的第三个可见单元格定义为 B 列中的变量
- c# - 合并 2 个 linq 查询,使用 1 的结果继续搜索
- javascript - 更改按钮上的文本
- mysql - 如何使用与另一个表不同的条件将一个表加入到自身中
- react-native - 标识符 'userInfo' 已经在 React-native 中声明