Home > Net >  String Comparison __Lt__ operator python:
String Comparison __Lt__ operator python:

Time:11-21

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

CodePudding user response:

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

  • Related