Why is bool a subclass of int?(为什么 bool 是 int 的子类?)
问题描述
当通过 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
但是为什么 bool 是 int 的子类呢?
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.
这篇关于为什么 bool 是 int 的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 bool 是 int 的子类?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
