Custom binary operations and getattr

133 Views Asked by At

I would like to implement a class with custom binary operators, such that

class One:
    def __lt__(self,other):
        return 1 < other

Python seems to be able to automatically create the reverse operation for the operators >, >=, <, <=, however, if I use the getattr() method instead, NotImplemented is returned:

>>> a = One()
>>> a < 2
True
>>> 2 > a # Works without explicit implementation
True

# Now using the getter:
>>> getattr(a, '__lt__')(2)
True
>>> getattr(2, '__gt__')(a) # Does not work as above
NotImplemented

What would be the proper way to make the getter work as well in this case? I know that for other operators, there is the respective reverse magic method, but the four mentioned above do not seem to have that.

0

There are 0 best solutions below