本文介绍了为什么是布尔int的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过存储memcached中一个布尔值的python-memcached的我注意到,它返回一个整数。检查库的code给我看,有其中 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外壳进行了测试,发现以下内容:

So I tested it in the python shell and noticed the following:

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

但为什么恰恰是布尔 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)....

推荐答案

从注​​释:// WWW .peterbe.com / PLOG /布尔-IS-INT

From a comment on http://www.peterbe.com/plog/bool-is-int

这是完全合乎逻辑的,如果你身边的时候bool类型是
  加入到了Python(大约在2.2或2.3)。

之前引入一个实际布尔型的,0和1分别在
  官方再presentation为真值,类似于C89。避免
  打破不必要的不​​理想,但工作code,新的bool类型
  工作就像0和1这超出了仅仅真值需要,
  但所有的积分操作。没有人会建议使用布尔
  导致数字的背景下,多数人也不会推荐测试
  平等确定真值,谁都想弄清楚硬
  方法到底有多少现有的code是这样的。因此,决定把
  真与假伪装成分别为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.

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

08-05 17:38