为什么在Python 3中,bool是int的子类?

2024-06-28 20:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

自从引入bool以来,它一直是int的子类,bool可以隐式地“转换”成整数:

>>> issubclass(bool, int)
True
>>> ['one', 'two'][False]
'one'
>>> ['one', 'two'][True]
'two'
>>> True/20
0.05

这是因为历史原因:与2.3API之前的版本兼容;据我所知,它一直保持在2.3到2.7之间。(这是从2011年起在this question中提到的)

但是,为什么在python3中仍然如此呢?我看不出有什么好处。而且没有理由为了向后兼容而保留它:Python3.0是一个破版;而且我不认为任何2.3之前的API仍然存在。在


Tags: 版本apifalsetrue原因整数历史this
2条回答

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.

去除bools作为数字并不是一个预期的语言方向。吉多不认为这会使语言变得更好。在

有用的例子:两个布尔值0,False和1,True可以表示任何二进制分区的2个部分。假设n个人回答m个问题,他们对每个问题的回答都被标记为“失败”或“通过”。我们创建一个包含n行和m(+1,表示id)列的数据表,代码fail/pass为0/1。然后,我们可以通过行和来计算每个问题的通过率,通过求和列来计算每个问题的通过次数。任何像样的分析软件都应该能够做到这一点或没有定制编程。在

Python3开发:我参加了讨论,并确信有很多破坏兼容性的建议被拒绝,而不是被接受。每一次改变都要自己付出代价。在

相关问题 更多 >