Python中是否只有一个True和False对象? [英] Is there only one True and one False object in Python?
问题描述
我知道Python保证NoneType
(即None
对象)只有一个实例,因此您可以安全地使用is None
来测试是否等于None
.
I know that Python guarantees that there is only one instance of NoneType
, the None
object, so that you can safely use is None
to test if something equals None
.
bool
True
和False
是否有同等的保证(即,每个实例只有一个实例)?
Is there an equivalent guarantee for bool
True
and False
(i.e. that there is only one instance of each)?
如果没有,为什么不呢?
If not, why not?
特别是,我注意到(n+0) is (0+n)
为range(-5, 257)
中的n提供True
,否则为False
.换句话说,零,前256个正整数和前5个负整数似乎已被预先缓存,并且不再进行实例化.我猜想这是解释器(在我的情况下为CPython)的选择,而不是语言的规范.而且bool
源自int
,所以我仍然想知道我对其他口译员会有什么期望.
In particular, I've noticed that (n+0) is (0+n)
gives True
for n in range(-5, 257)
and False
otherwise. In other words, zero, the first 256 positive and the first 5 negative integers seem to be pre-cached and are not instanced again. I am guessing that that's a choice of the interpreter (CPython, in my case) and not a specification of the language. And bool
derives from int
, so I still have to wonder about what expectations I can have with other interpreters.
编辑:为澄清起见,由于这似乎引起了很多混乱,我的目的不是不是来测试值的布尔值解释.为此,我永远不会使用is True
或is False
.我的意图是能够在一个变量中区分出False
和其他所有内容,该变量可以具有多种类型的值,包括空字符串,零和None
,对于True
同样.我本人是一位经验丰富的程序员,当我看到"if booleanvar == True"时会畏缩.
To clarify, since this seems to have generated a lot of confusion, my intention is not to test the boolean interpretation of a value. For that I would never use is True
or is False
. My intention is to be able to tell apart False
from everything else, in a variable that can have values of several types including empty strings, zeros, and None
, and similarly for True
. I'm myself an experienced programmer, of the kind who cringes when I see "if booleanvar == True".
重复说明:有人质疑此问题与()不会回答这个问题;他们只是声明bool
是int
的子类,主要区别在于repr
,而不能保证True
和False
是唯一的.
NOTE ON DUPLICATES: The questions this one was alleged to be a duplicate of (this and this) don't answer this question; they merely state that bool
is a subclass of int
that differ mainly in their repr
, not if True
and False
are guaranteed to be unique.
此外,请注意,这不是关于名称 True
和False
所绑定的问题,而是关于
Also, note that it's not a question about what the names True
and False
are bound to, but about the instances of the class bool
.