为什么 bool 是 int 的子类?

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

问题描述

当通过 python-memcached 将 bool 存储在 memcached 中时,我注意到它以整数形式返回.检查库的代码告诉我有一个地方检查 isinstance(val, int) 以将值标记为整数.

When storing a bool in memcached through python-memcached I noticed that it's returned as an integer. Checking the code of the library showed me that there is a place where isinstance(val, int) is checked to flag the value as an integer.

所以我在 python shell 中对其进行了测试,并注意到以下内容:

So I tested it in the python shell and noticed the following:

>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True

但是为什么 boolint 的子类呢?

But why exactly is bool a subclass of int?

这是有道理的,因为布尔值基本上是一个 int,它可以只取两个值,但它需要的操作/空间比实际整数少得多(没有算术,只有一位存储空间)....

It kind of makes sense because a boolean basically is an int which can just take two values but it needs much less operations/space than an actual integer (no arithmetics, only a single bit of storage space)....


解决方案

来自对 http://www 的评论.peterbe.com/plog/bool-is-int

这是完全合乎逻辑的,如果你在 bool 类型出现的时候就在附近添加到 python(有时在 2.2 或 2.3 左右).

It is perfectly logical, if you were around when the bool type was added to python (sometime around 2.2 or 2.3).

在引入实际的布尔类型之前,0 和 1 是真值的官方表示,类似于 C89.避免不必要地破坏非理想但有效的代码,新的 bool 类型需要像 0 和 1 一样工作.这不仅仅是真值,但所有积分运算.没有人会推荐使用布尔值导致数字上下文,大多数人也不建议测试平等决定真值,没有人想找出困难有多少现有的代码就是这样的.因此做出的决定True 和 False 分别伪装成 1 和 0.这仅仅是一个语言演变的历史产物.

Prior to introduction of an actual bool type, 0 and 1 were the official representation for truth value, similar to C89. To avoid unnecessarily breaking non-ideal but working code, the new bool type needed to work just like 0 and 1. This goes beyond merely truth value, but all integral operations. No one would recommend using a boolean result in a numeric context, nor would most people recommend testing equality to determine truth value, no one wanted to find out the hard way just how much existing code is that way. Thus the decision to make True and False masquerade as 1 and 0, respectively. This is merely a historical artifact of the linguistic evolution.

感谢 dman13 的精彩解释.

Credit goes to dman13 for this nice explanation.

相关文章