为什么 bool 是 int 的子类?

Why is bool a subclass of int?(为什么 bool 是 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

但是为什么 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.

这篇关于为什么 bool 是 int 的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)