为什么表达式 0 <0 == 0 在 Python 中返回 False? [英] Why does the expression 0 &lt; 0 == 0 return False in Python?

查看:63
本文介绍了为什么表达式 0 <0 == 0 在 Python 中返回 False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 Python 2.6 中的 Queue.py,我发现这个结构有点奇怪:

def full(self):"""如果队列已满则返回True,否则返回False(不可靠的!)."""self.mutex.acquire()n = 0 

如果 maxsize 为 0,则队列永远不会满.

我的问题是它如何适用于这种情况?如何 0 <0 == 0 被认为是 False?

<预><代码>>>>0<0 == 0错误的>>>(0) <(0 == 0)真的>>>(0 <0) == 0真的>>>0<(0 == 0)真的

解决方案

我相信 Python 对关系运算符序列有特殊情况处理,使范围比较易于表达.能够说 0 < 好得多.x <= 5 而不是说 (0 .

这些被称为链式比较.这是他们文档的链接.

对于您谈到的其他情况,括号强制一个关系运算符在另一个之前应用,因此它们不再是链式比较.由于 TrueFalse 的值为整数,因此您可以从括号中的版本中获得答案.

Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange:

def full(self):
    """Return True if the queue is full, False otherwise
    (not reliable!)."""
    self.mutex.acquire()
    n = 0 < self.maxsize == self._qsize()
    self.mutex.release()
    return n

If maxsize is 0 the queue is never full.

My question is how does it work for this case? How 0 < 0 == 0 is considered False?

>>> 0 < 0 == 0
False
>>> (0) < (0 == 0)
True
>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True

解决方案

I believe Python has special case handling for sequences of relational operators to make range comparisons easy to express. It's much nicer to be able to say 0 < x <= 5 than to say (0 < x) and (x <= 5).

These are called chained comparisons. And that's a link to the documentation for them.

With the other cases you talk about, the parenthesis force one relational operator to be applied before the other, and so they are no longer chained comparisons. And since True and False have values as integers you get the answers you do out of the parenthesized versions.

这篇关于为什么表达式 0 <0 == 0 在 Python 中返回 False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆