为什么 bool 是 int 的子类?

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

因此,我在 python shell 中测试了它,并注意到以下内容:

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

但是为什么 boolint的一个子类呢?

这是有道理的,因为布尔值基本上是一个整型数,它只需要两个值,但它需要的操作/空间要比实际的整型数少得多(没有算术,只有一个位的存储空间) ..。

19720 次浏览

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

It is perfectly logical, if you were around when the bool type was added to python (sometime around 2.2 or 2.3).

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.

Credit goes to dman13 for this nice explanation.

See PEP 285 -- Adding a bool type. Relevent passage:

6) Should bool inherit from int?

=> Yes.

In an ideal world, bool might be better implemented as a separate integer type that knows how to perform mixed-mode arithmetic. However, inheriting bool from int eases the implementation enormously (in part since all C code that calls PyInt_Check() will continue to work -- this returns true for subclasses of int).

Can also use help to check the Bool's value in Console:

help(True)

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(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