为什么 bool 是 int 的子类?
- 2025-01-22 08:45:00
- admin 原创
- 65
问题描述:
当通过 python-memcached 将布尔值存储在 memcached 中时,我注意到它返回为整数。检查库的代码后,我发现有一个地方isinstance(val, int)
被选中以将值标记为整数。
因此我在 python shell 中对其进行了测试,并注意到了以下情况:
>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True
但为什么它确实是bool
的子类int
?
这是有道理的,因为布尔值基本上是一个只能取两个值的整数,但它需要的运算/空间比实际整数少得多(没有算术,只有一位存储空间)......
解决方案 1:
来自http://www.peterbe.com/plog/bool-is-int上的评论
如果你在 bool 类型添加到 python 时(大约在 2.2 或 2.3 左右)就存在,那么这是完全合乎逻辑的。
在引入实际的 bool 类型之前,0 和 1 是真值的官方表示,类似于 C89。为了避免不必要地破坏非理想但有效的代码,新的 bool 类型需要像 0 和 1 一样工作。这不仅仅是真值,而是所有积分运算。没有人会建议在数字上下文中使用布尔结果,大多数人也不会建议测试相等性来确定真值,没有人想用困难的方式找出现有代码中有多少是那样的。因此,决定将 True 和 False 分别伪装成 1 和 0。这只是语言进化的历史产物。
感谢 dman13 的精彩解释。
解决方案 2:
参见PEP 285 -- 添加 bool 类型。相关段落:
6)bool 应该从 int 继承吗?
=> 是的。
在理想情况下,bool 最好实现为一个知道如何执行混合模式算术的单独整数类型。但是,从 int 继承 bool 可以大大简化实现(部分原因是所有调用 PyInt_Check() 的 C 代码将继续工作 - 这对 int 的子类返回 true)。
解决方案 3:
也可以使用它在控制台中help
检查的值:Bool
帮助(真)
help(True)
Help on bool object:
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
帮助(假)
help(False)
Help on bool object:
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object