在Python 2.x中,这不能保证,因为可以重新分配True和False。但是,即使发生这种情况,boolean True和boolean False仍然会正确返回进行比较。
在Python 3.x True和False是关键字,将始终等于1和0。
正常情况下在Python 2中,总是在Python 3:
False对象的类型是bool,它是int的子类:
object
|
int
|
bool
这是在你的例子中,[‘zero’,’one’] [False]工作的唯一原因。它不适用于不是整数子类的对象,因为列表索引只能使用整数或定义了__index__方法的对象(感谢mark-dickinson)。
编辑:
There are two types of integers: […] Integers (int) […] Booleans (bool)
并在布尔子节中:
Booleans: These represent the truth values False and True […] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings “False” or “True” are returned, respectively.
因此,在Python 2.6和3中,布尔值被明确地视为整数。
所以你是安全的,直到Python 4出现。 😉