Souvik Ray
Souvik Ray

Reputation: 3028

Unable to implement __lt__ (less than) method to sort a list of class objects

I am trying to use _lt__ method to compare class objects and sort accordingly.But haven't been able to do so far

class Test:

    def __init__(self,x):
        self.x = x

    def __lt__(self,other):
        return self.x < other.x

t1 = Test(10)
t2 = Test(12)
lis = [t1,t2]
lis.sort()
print(lis)

I am getting output as

[<__main__.Test object at 0x7fd4c592fb70>, <__main__.Test object at 0x7fd4c592fb38>]

I thought maybe I need to give a string representation to the object.So I did

def __str__(self):
    return "{}".format(self.x)

Still I am getting the same output

[<__main__.Test object at 0x7f212594bac8>, <__main__.Test object at 0x7f212594bc50>]

What am I doing wrong?

Upvotes: 0

Views: 132

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46901

you are doing almost everything right; the thing is just that objects inside a list are represented by __repr__ and not __str__:

class Test:

    def __init__(self,x):
        self.x = x

    def __lt__(self,other):
        return self.x < other.x

    def __repr__(self):
        return "{}".format(self.x)

t1 = Test(10)
t2 = Test(12)
lis = [t1,t2]
lis.sort()
print(lis)  # [10, 12]

Upvotes: 1

Related Questions