首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么bool是int的子类?

为什么bool是int的子类?
EN

Stack Overflow用户
提问于 2011-11-17 22:43:37
回答 3查看 18.2K关注 0票数 88

在通过python-memcached在memcached中存储布尔值时,我注意到它是以整数形式返回的。通过检查该库的代码,我发现有一个地方可以检查isinstance(val, int),以便将值标记为整数。

因此,我在python shell中对其进行了测试,并注意到以下几点:

代码语言:javascript
复制
>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True

但是为什么boolint的子类呢?

这在某种程度上是有意义的,因为布尔值基本上是一个int,它只能接受两个值,但它需要的操作/空间比实际的整数少得多(没有算术,只有一位存储空间)……

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-11-17 22:46:32

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

如果你在bool类型被添加到

(有时在2.2或2.3左右)的时候,这是非常合乎逻辑的。

在引入实际的布尔类型之前,0和1是真值的官方表示,类似于C89。为了避免不必要地破坏非理想但有效的代码,新的bool类型需要像0和1一样工作。这不仅仅是真值,而是所有的整数运算。没有人会建议在数字上下文中使用布尔结果,也没有人会建议通过测试相等来确定真值,也没有人想要艰难地找出现有代码有多少是这样的。因此,将True和False分别伪装为1和0的决定。这只是语言演变的历史产物。

这要归功于dman13的这个很好的解释。

票数 104
EN

Stack Overflow用户

发布于 2011-11-17 22:47:53

参见PEP 285 -- Adding a bool type。相关段落:

6) bool应该从int继承吗?

=>是的。

在理想情况下,将bool实现为知道如何执行混合模式算术的单独整数类型可能更好。但是,从int继承bool极大地简化了实现(部分原因是所有调用PyInt_Check()的C代码都将继续工作--对于int的子类,这将返回true )。

票数 31
EN

Stack Overflow用户

发布于 2018-01-23 10:40:56

也可以在控制台中使用help检查Bool的值:

帮助(True)

代码语言:javascript
复制
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
 |  

帮助(假)

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8169001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档