OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Issue?


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180822/708a349e/attachment.html>