list.sort()如何与重载运算符一起使用?

时间:2017-12-14 01:52:27

标签: python oop

代码在这里:

class WeirdSortee:
    def __init__(self, string, number, sort_num):
        self.string = string
        self.number = number
        self.sort_num = sort_num
    def __lt__(self, object):
        if self.sort_num:
            return self.number < object.number
        return self.string < object.string
    def __repr__(self):
        return"{}:{}".format(self.string, self.number)

a = WeirdSortee('a', 4, True)
b = WeirdSortee('b', 3, True)
c = WeirdSortee('c', 2, True)
d = WeirdSortee('d', 1, True)
l = [a,b,c,d]
l.sort() #returns [d:1, c:2, b:3, a:4]
for i in l:
    i.sort_num = False
l.sort()
print(l) #returns [a:4, b:3, c:2, d:1]

我知道&lt; b&lt; c&lt;但是如何对自我和对象进行排序?在这种情况下,对象和自我是什么?

0 个答案:

没有答案