Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading less than in python

I've been fiddling with overloading operators in python and I've come across a question.

So I have a class that has values in which I want to use for a comparison.

class comparison:

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

    ...

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

which overloads the operator for less than. I made conditions on other such as what type it must be.

An example would be

x = comparison(2)
x < 1 #--> False
x < 3 #--> True

My question would be how could I check on the first part of the comparison? I'm trying to limit the first part to something specific.

An example would be

7 < x # --> I don't want the first one to be an int
like image 495
Same Avatar asked Dec 04 '25 09:12

Same


1 Answers

To do this, you can override the __gt__ method.

class comparison:
    ...
    def __gt__(self, other):
        ...

7<comparison(2) will then get transformed in the call comparison(2).__gt__(7), which you can override.

like image 153
pppery Avatar answered Dec 06 '25 23:12

pppery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!