python - 为什么 bool 是 int 的子类?

标签 python boolean

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

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

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

但是为什么 boolint 的子类呢?

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

最佳答案

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

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

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 的精彩解释。

关于python - 为什么 bool 是 int 的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8169001/

相关文章:

C++ sizeof 与 bool

python - 在 Python 中使用多个条目格式化字典的正确方法

具有可写属性的类型的 Python 注释

python - "SyntaxError: unexpected EOF while parsing"简单的 python print() 方法

jquery - Bootstrap 开关返回 "on/off"而不是 "true/false"

java - 我正在尝试用 Java 将与投注相关的组件添加到我的游戏中,但程序在要求投注金额后停止工作

activerecord - Rails 4.x 如何使用 activerecord 查询 boolean 值?

python - 为什么我的数据库不能在此 Python/Django 应用程序中运行?

python - 根据某些字符在python中拆分行

java - 使用默认 ObjectMapper 后 boolean JSON 参数为 false