Why compare twice?

class Student(object):


    def __init__(self, name, score):
        self.name = name
        self.score = score


    def __str__(self):
        return '(%s: %s)' % (self.name, self.score)


    __repr__ = __str__


    def __lt__(self, s):
        #print(self, '--', s)
        if(self.score<s.score):
            print(self, '<', s)
            return True
        if(self.score>s.score):
            print(self, '>', s)
            return False
        if(self.score==s.score):
            if(self.name>s.name):
                print(self, '>', s)
                return False
            if(self.name<s.name):
                print(self, '<', s)
                return True
            if(self.name==s.name):
                print(self, '==', s)
                return False
                
    def __eq__(self, s):
        return (self.score == s.score) and (self.name == s.name)
    def __gt__(self, s):
        return not ((self == s) or (self < s))
    def __le__(self, s):
        return ((self == s) or (self < s))
    def __ge__(self, s):
        return ((self == s) or (self > s))
    def __nq__(self, s):
        return not (self == s)


L = [Student('Tim', 22), Student('Bob', 33), Student('Kevin', 11), 
Student('Alice', 11)]

print(sorted(L))


Output:
(Bob: 33) > (Tim: 22)
(Kevin: 11) < (Bob: 33)
(Kevin: 11) < (Bob: 33)
(Kevin: 11) < (Tim: 22)
(Alice: 11) < (Tim: 22)
(Alice: 11) < (Kevin: 11)
[(Alice: 11), (Kevin: 11), (Tim: 22), (Bob: 33)]


Best regards,
Xiaofeng
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to