python - 为什么 bool 是 Python 3 中 int 的子类?

标签 python python-3.x boolean

<分区>

自从引入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 认为这不会让语言变得更好。

关于python - 为什么 bool 是 Python 3 中 int 的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309531/

相关文章:

python - 如何在不使用 ffmpeg 的情况下将 python 上的视频转换为 .mp4?

java - Magic 8 Ball 始终不打印 java

bash - Bash 中的 boolean 运算符(&&、-a、||、-o)

python - 如何找到图像中数字的中心坐标

python - 调用不带括号的函数python的目的

python - 使用 Python 将基于 pdf 的网页下载为 pdf

c++ - 将 reinterpret_cast 与 bool 一起使用

python - PyQt5可检查组合框: display list of checked items

python - 使用正则表达式匹配文字记录中的姓名、对话和 Action

python - 不知道要在 try.. except.. 中放入什么来处理不存在的字符串