重载小于python中的重载

重载小于python中的重载,python,comparison,operator-overloading,Python,Comparison,Operator Overloading,我一直在处理python中的重载运算符,我遇到了一个问题 所以我有一个类,它有一些值,我想在其中进行比较 class comparison: def __init__(self, x): self.x = x ... def __lt__(self,other): return self.x < other 类比较: 定义初始化(self,x): self.x=x ... 定义(自身、其他): 返回self.x

我一直在处理python中的重载运算符,我遇到了一个问题

所以我有一个类,它有一些值,我想在其中进行比较

class comparison:

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

    ...

    def __lt__(self,other): 
        return self.x < other
类比较:
定义初始化(self,x):
self.x=x
...
定义(自身、其他):
返回self.x<其他
它使运算符重载的时间少于。我提出了其他条件,比如它必须是什么类型

例如

x = comparison(2)
x < 1 #--> False
x < 3 #--> True
7 < x # --> I don't want the first one to be an int
x=比较(2)
x<1#-->错误
x<3#-->正确
我的问题是如何检查比较的第一部分? 我想把第一部分限制在一些具体的事情上

例如

x = comparison(2)
x < 1 #--> False
x < 3 #--> True
7 < x # --> I don't want the first one to be an int
7我不希望第一个是int

要执行此操作,您可以覆盖
\uu gt\uu
方法

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

7如前所述,
x<7
应该抛出
TypeError:unorderable types
EDIT:interest,它不会在Python2上抛出该错误,但在Python3上会抛出该错误。@juanpa.arrivillaga在Python2中,一切都是有序的(例如,您可以比较函数和整数:
(lambda x:x+1)
False
.In
7@DYZ所以它使用的是
7.\uu gt\uuu