I have seen similar questions, but they did not answer why python __lt__ has higher priority than __gt__?
Quick example, let me give a superclass and a subclass:
class Person(object):
id = 0
def __init__(self, name):
self.name = name
self.id = Person.id
Person.id += 1
def __str__(self):
return self.name
def __lt__(self, other):
return self.id < other.id
class SubPerson(Person):
def __gt__(self, other):
return self.name > other.name
Here in superclass Person, I created a __lt__ method, to compare based on Person's self.id. In sub class SubPerson, I created a __gt__ method to compare based on the self.name.
What I found is that if I created a number of SubPerson instances in a list:
s1 = SubPerson('WWW'); s1.id = 14
s2 = SubPerson('XXX'); s2.id = 12
s3 = SubPerson('YYY'); s3.id = 11
s4 = SubPerson('ZZZ'); s4.id = 13
lst2 = [s2, s1, s4, s3]
lst2.sort()
print([i.__str__() for i in lst2]) # >>> ['YYY', 'XXX', 'ZZZ', 'WWW']
What I found is that:
if __lt__ is defined in superclass, then even if you define __gt__ in subclass, it will still sort by the __lt__ method in superclass
But if it is the other way around, define __gt__ in superclass and __lt__ in subclass, then it will then sort by __lt__ in subclass
If the two method names are the same (both lt or both gt), obviously, the subclass will override superclass, as it should be.
But it seems when they are different, it follows a different rule: by whatever __lt__ defines. I've also noticed that even if in one class, if both __lt__ and __gt__ are defined (based on different things, it will still sort by __lt__ method)
SO back to my question, is my observation true or not? and since I am a beginner, and I have not read through the whole python documents, can somebody point me out where in the documents that this rule is written.
__gt__method??__lt__from the parent.__lt__in the parent, and sub will then sort by__gt__.__gt__) when the left hand side doesn't support the direct (__lt__) comparison. You benefit by accident. In practice, you should really only define__eq__and__lt__, then decorate the class withfunctools.total_orderingto define the other comparisons in terms of them.