在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ python 定義__lt__方法沒有定義__gt__,當(dāng)使用>時(shí)自動(dòng)調(diào)用

python 定義__lt__方法沒有定義__gt__,當(dāng)使用>時(shí)自動(dòng)調(diào)用了__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

當(dāng)s1<s2時(shí)調(diào)用__lt__方法沒有問題,問題是當(dāng)調(diào)用>時(shí)貌似也調(diào)用了__lt__,但是結(jié)果貌似取了一個(gè)非操作。這是python 的什么特性?什么情況下會(huì)出現(xiàn)這種結(jié)果

回答
編輯回答
練命

參考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 假定<> 是相反的操作, 如果其中一個(gè)沒有定義, 使用另一個(gè)的時(shí)候就調(diào)用定義的一個(gè), 只是把對(duì)比的對(duì)象交換一下位置. 同樣的特性還發(fā)生在 <=>= 以及 ==!=.

2018年5月10日 23:36