Python中是否只有一个True和False对象? [英] Is there only one True and one False object in Python?

查看:157
本文介绍了Python中是否只有一个True和False对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道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)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 Trueis 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".

重复说明:有人质疑此问题与()不会回答这个问题;他们只是声明boolint的子类,主要区别在于repr,而不能保证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.

此外,请注意,这不是关于名称 TrueFalse所绑定的问题,而是关于>类的 instances 的问题.

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.

推荐答案

从文档中(

布尔值

这些代表真值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

这篇关于Python中是否只有一个True和False对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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