Python rich comparison method comprises __lt__、__gt__
respectively: less than, greater than, the corresponding operation operators are: "<", ">." Whether you like a normal number crunching, like reciprocal relationship exists between these two methods do?
Python no __lt __, __ What is the relationship between gt__ forced these two methods, but suggested __lt__ and __gt__ is reciprocal, developers can define their own needs based on business logic. Let's analyze verification:
- When a custom class defines two methods, "<", ">", respectively, and calls __lt__ __gt__ method;
- When a custom class defines methods __lt__, undefined __gt__ method, ">" Comparative __lt__ method is invoked, but negated recall value. Case:
>>> class Car():
def __init__(self,carname,oilcp100km, price):
self.carname,self.oilcp100km,self.price = carname,oilcp100km, price
def __lt__(self,other):
print("execute __lt__")
return self.price<other.price
>>>
>>> car1,car2,car3,car4 = Car('爱丽舍',8,10),Car('凯美瑞',7,27),Car('爱丽舍',8,10),Car('途观',12,27)
>>>
>>> car1>car2
execute __lt__
False
>>> car1<car2
execute __lt__
True
>>>
- When a custom class defines methods __gt__, undefined __lt__ method, "<" Comparative __gt__ method is invoked, but negated recall value. Case:
>>> class Car():
def __init__(self,carname,oilcp100km, price):
self.carname,self.oilcp100km,self.price = carname,oilcp100km, price
def __gt__(self,other):
print("execute __gt__")
return self.price>other.price
>>> car1,car2,car3,car4 = Car('爱丽舍',8,10),Car('凯美瑞',7,27),Car('爱丽舍',8,10),Car('途观',12,27)
>>> car1<car2
execute __gt__
True
>>> car1>car2
execute __gt__
False
>>>
Through the above cases, we know that when __lt __, __ when gt__ methods are defined, "<", ">", respectively call __lt__ and __gt__ method, when a definition of another undefined, undefined operations performed calls upon the already defined methods negated. This relationship with __eq__ and __ne__ still quite different.
Old ape Python, with the old ape learn Python!
Blog address: https: //blog.csdn.net/LaoYuanPython
please support, thumbs up, comment and processing concern! Thank you!