Python 中只有一个 True 和一个 False 对象吗?

2022-01-19 00:00:00 python object boolean instance

问题描述

我知道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 TrueFalse 是否有等效的保证(即每个实例只有一个)?

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) 给出 True for n inrange(-5, 257)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 Trueis False.我的目的是能够将 False 与其他所有内容区分开来,在一个变量中,该变量可以具有多种类型的值,包括空字符串、零和 None,类似地正确.我自己是一位经验丰富的程序员,当我看到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".

关于重复的注意事项:这个问题据称与 (this 和 this) 不要回答这个问题;他们只是声明 boolint 的子类,主要区别在于它们的 repr,而不是 if TrueFalse保证唯一.

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.

另外,请注意,这不是关于 names TrueFalse 绑定到什么的问题,而是关于 instances 的问题 类的 bool.

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.


解决方案

来自文档(https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy):

布尔值

这些代表真值 False 和 True.表示 False 和 True 值的两个对象是唯一的布尔对象.

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects.

只有两个对象,任何产生布尔值的计算都会产生这两个现有对象之一:

There are only two objects, any computation producing a boolean will produce one of those two existing objects:

>>> (1 == 1) is True
True
>>> (1 == 0) is False
True

相关文章