自从引入bool
以来,它就是int
的子类,bools可以隐式地“转换”成整数:
>>> issubclass(bool, int)
True
>>> ['one', 'two'][False]
'one'
>>> ['one', 'two'][True]
'two'
>>> True/20
0.05
这是出于历史原因:与 pre-2.3 API 的兼容性;我知道它从 2.3 保留到 2.7。 (这在 2011 年的 this question 中得到解决)
但是,为什么在 Python 3 中仍然如此?我看不出有什么好处。并且没有理由为了向后兼容而保留它:Python 3.0 是一个突破性的版本;而且我不认为任何 2.3 之前的 API 仍然存在。
来自original bool PEP :
Should we strive to eliminate non-Boolean operations on bools in the
future, through suitable warnings, so that for example True+1 would
eventually (in Python 3000) be illegal?
=> No.
There's a small but vocal minority that would prefer to see "textbook"
bools that don't support arithmetic operations at all, but most
reviewers agree with me that bools should always allow arithmetic
operations.
稍后在同一文档中:
Because of backwards compatibility, the bool type lacks many
properties that some would like to see. For example, arithmetic
operations with one or two bool arguments is allowed, treating False
as 0 and True as 1. Also, a bool may be used as a sequence index.
I don't see this as a problem, and I don't want evolve the language in
this direction either. I don't believe that a stricter interpretation
of "Booleanness" makes the language any clearer.
删除 boolean 值不是预期的语言方向。 Guido 认为这不会让语言变得更好。