我想做这样的事情:
MyClass > 200 < 400
该类实现了 __gt__()
和 __lt__()
方法,它们都返回 self
.
class MyClass:
...
def __gt__(self, value):
DoCompareStuff(self, value)
return self
def __lt__(self, value):
DoCompareStuff(self, value)
return self
...
它将进行第一次评估,MyClass > 200
, 但从不执行第二个 MyClass < 400
.似乎 Python 正在对返回值做一些事情,比如让它成为 True
。或 False
.有没有办法做我想在这里做的事情?
请您参考如下方法:
用于比较的运算符链接(参见 the docs)意味着
MyClass > 200 < 400
实际上被评估为:
(MyClass > 200) and (200 < 400)
因此,MyClass
和 400
从未进行过比较。相反,您想要:
200 < MyClass < 400
被评估为:
(200 < MyClass) and (MyClass < 400)
举个简单的例子:
>>> class Demo(object):
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other
def __gt__(self, other):
return self.value > other
>>> demo = Demo(250)
>>> 200 < demo < 400
True
注意这里的__lt__
和__gt__
实现有一个 bool 返回(True
或False
),而不是返回 self
(这将导致意外行为)。