python 定义__lt__方法没有定义__gt__,当使用>时自动调用了__lt__?

新手上路,请多包涵
class SavingsAccount(object):
    def __init__(self, name, pin, balance = 0.0):
        self._name = name
        self._pin = pin
        self._balance = balance
        
    def __lt__(self,other):
        print("this is <")
        return self._name < other._name

s1 = SavingsAccount("Ken","1000",0)
s2 = SavingsAccount("Bill", "1001",30)  

s1<s2
this is <
False

s1>s2
this is <
True

当s1<s2时调用__lt__方法没有问题,问题是当调用>时貌似也调用了__lt__,但是结果貌似取了一个非操作。这是python 的什么特性?什么情况下会出现这种结果

阅读 2.9k
1 个回答

参考PEP207:

If the object on the left side of the operator does not define an appropriate rich comparison operator (either at the C level or with one of the special methods, then the comparison is reversed, and the right hand operator is called with the opposite operator, and the two objects are swapped. This assumes that a < b and b > a are equivalent, as are a <= b and b >= a, and that == and != are commutative (e.g. a == b if and only if b == a).

python3 假定<> 是相反的操作, 如果其中一个没有定义, 使用另一个的时候就调用定义的一个, 只是把对比的对象交换一下位置. 同样的特性还发生在 <=>= 以及 ==!=.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题