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

why defining only __lt__ makes > operation possible?

class Node:
    def __init__(self,a,b):
        self._a=a
        self._b=b
    def __lt__(self,other):
        return self._a<other._a


a=Node(1,2)
b=Node(0,4)
print(a>b)

The code above shows True.

class Node:
    def __init__(self,a,b):
        self._a=a
        self._b=b
    def __lt__(self,other):
        return self._a<other._a
    def __eq__(self,other):
        return self._a==other._a

a=Node(1,2)
b=Node(0,4)
print(a>=b)

The code above shows TypeError: ‘<=’ not supported between instances of ‘Node’ and ‘Node.

Why defining only lt makes >(which is gt) operation possible?
why defining both lt and eq makes <= impossible?

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 Python docs dictates:

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection.

So if the left-hand-side argument doesn’t implement a comparison operator while the right-hand-side implements its reflection, that reflection is called instead. This also explains why Python doesn’t combine __lt__() and __eq__() into __le__() — it simply isn’t considered.

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