相较于 a.is_equal(b), a.is_greater_than(b) 这种语法的函数调用来进行对象的对比, 使用运算符的比较 a == b, a > b 这样的语法更加直观。
Python 种提供了一系列的魔术方法, 来实现对象的对比。
方法 | 说明 | 运算符 |
__eq__(self, other) | 定义相等运算符的行为 | == |
__ne__(self, other) | 定义不等式运算符的行为 | != |
__lt__(self, other) | 定义小于运算符的行为 | < |
__le__(self, other) | 定义小于或等于运算符的行为 | <= |
__gt__(self, other) | 定义大于运算符的行为 | > |
__ge__(self, other) | 定义大于 |