String Comparison __Lt__ operator python:

I want to be able to compare 2 objects based on their attribute – Size.
Is the following correct? because it does not work

def __lt__(self, other): 
    if self.size == "small" and other.size == "big":
        return other.size > self.size
    if self.size == "small" and other.size == "medium":
        return other.size > self.size
    if self.size == "medium" and other.size == "big":
        return other.size > self.size

Thanks

>Solution :

The issue is that you need to return booleans :

def __lt__(self, other): 
    if self.size == "small" and other.size in ["big", "medium"]:
        return True
    if self.size == "medium" and other.size == "large":
        return True
    if ...

NB. you need to handle all possibilities

Leave a Reply