Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading