Python允许像x > y > z
这样的表达式,根据文档,除了y
只计算一次之外,它等同于(x > y) and (y > z)
。(https://docs.python.org/3/reference/expressions.html)
然而,如果我自定义比较函数,这似乎就会中断。例如,假设我有下面的类:(很抱歉代码块很大,但是一旦你读取了__eq__
方法,剩下的就很简单了。)
class CompareList(list):
def __repr__(self):
return "CompareList([" + ",".join(str(x) for x in self) + "])"
def __eq__(self, other):
if isinstance(other, list):
return CompareList(self[idx] == other[idx] for idx in xrange(len(self)))
else:
return CompareList(x == other for x in self)
def __ne__(self, other):
if isinstance(other, list):
return CompareList(self[idx] != other[idx] for idx in xrange(len(self)))
else:
return CompareList(x != other for x in self)
def __gt__(self, other):
if isinstance(other, list):
return CompareList(self[idx] > other[idx] for idx in xrange(len(self)))
else:
return CompareList(x > other for x in self)
def __ge__(self, other):
if isinstance(other, list):
return CompareList(self[idx] >= other[idx] for idx in xrange(len(self)))
else:
return CompareList(x >= other for x in self)
def __lt__(self, other):
if isinstance(other, list):
return CompareList(self[idx] < other[idx] for idx in xrange(len(self)))
else:
return CompareList(x < other for x in self)
def __le__(self, other):
if isinstance(other, list):
return CompareList(self[idx] <= other[idx] for idx in xrange(len(self)))
else:
return CompareList(x <= other for x in self)
现在我可以做一些有趣的事情了,比如CompareList([10, 5]) > CompareList([5, 10])
,它将正确地返回CompareList([True,False])
然而,链接这些操作并不能很好地工作:
low = CompareList([1])
high = CompareList([2])
print(low > high > low) # returns CompareList([True])
为什么不行?这里面到底发生了什么?我知道它不等同于(low > high) > low
= (False > low)
(因为它将返回False)。它可以是low > (high > low)
,但就操作符优先级(通常是从左到右)而言,这没有任何意义。
发布于 2016-05-10 22:18:34
Python允许像
x > y > z
这样的表达式,根据文档,它等同于(x > y) and (y > z)
,只是y
只计算一次。
根据这一点,low > high > low
将相当于(low > high) and (high > low)
。
>>> x = low > high # CompareList([False])
>>> y = high > low # CompareList([True])
>>> x and y
CompareList([True])
有关x and y的文档的更多信息
x and y
:如果x
为false,则为x
,否则为y
在上面的例子中:
>>> x is False
False
>>> x if x is False else y # x and y
CompareList([True])
因此,当您执行x and y
时,它将返回y
,即CompareList([True])
。
发布于 2016-05-10 22:16:30
您应该从比较方法中返回一个布尔值。
引用documentation for "rich comparison" methods
按照惯例,如果比较成功,则返回False和True。但是,这些方法可以返回任何值,因此如果在布尔上下文中使用比较运算符(例如,在if语句的条件下),Python将对该值调用bool()以确定结果是true还是false。
要对此案例进行分析,请执行以下操作:
exp1 = low > high
print(exp1)
print(bool(exp1))
exp2 = high > low
print(exp2)
print(bool(exp2))
会给你带来
CompareList([False])
True
CompareList([True])
True
现在我们做最后一次操作并打印出结果
print(exp1 and exp2)
因为这两个值的计算结果都是True
,所以您将得到
CompareList([True])
https://stackoverflow.com/questions/37140933
复制相似问题