0

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.

John Titor
  • 461
  • 3
  • 13
  • 1
    Python doesn't make those attributes exist, it deals with their absence. If you want all of the comparison methods to exist, see https://docs.python.org/3/library/functools.html#functools.total_ordering – jonrsharpe Apr 05 '20 at 16:19
  • `getattr(2, '__gt__')` retrieves the `__gt__` operator for POD integers and invokes it with an argument that doesn't inherit from `Integer`. That's something different than some auto-generated `__gt__` oeprator on class `One`. – starturtle Apr 05 '20 at 16:27
  • https://docs.python.org/3/reference/datamodel.html#object.__lt__ – wwii Apr 05 '20 at 16:32

0 Answers0