如果您不明白为什么bool是一个有效的索引参数:这只是为了使bool是{}的子类而在Python中它是一个数值类型。在
如果你问为什么bool首先是一个数字类型,那么你必须明白bool在旧版本的Python中并不存在,人们转而使用int。在
我将补充一些历史性的论点。首先,在Guido van Rossum(又名BDFL)blogpost:The History of Python: The history of ^{}, ^{} and ^{}中对python中bool的添加进行了简要描述。类型是通过PEP 285添加的。在
政治公众人物计划包含用于该决策的实际理由。我将引用下面的政治公众人物部分。在4) 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.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). Also, I believe this is right in terms of
substitutability: code that requires an int can be fed a bool
and it will behave the same as 0 or 1. Code that requires a
bool may not work when it is given an int; for example, 3 & 4
is 0, but both 3 and 4 are true when considered as truth
values.Because bool inherits from int, True+1 is valid and equals 2, and
so on. This is important for backwards compatibility: because
comparisons and so on currently return integer values, there's no
way of telling what uses existing applications make of these
values.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.
摘要:向后兼容性:有很多代码已经使用ints0和{}来表示False和{},其中一些代码在数值计算中使用了这些值。在
拥有一个“非教科书”类型并不是什么大问题
Python社区中的许多人都想要这些特性
BDFL如是说。在