且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在 Python 中 1 == True 但 2 != True?

更新时间:2022-10-31 20:32:15

因为 Python 中的 Boolean 是整数的子类型.来自文档:

布尔值是两个常量对象 False 和 True.它们用于表示真值(尽管其他值也可以被视为假或真).在数字上下文中(例如,当用作算术运算符的参数时),它们的行为分别类似于整数 0 和 1.内置函数 bool() 可用于将任何值转换为布尔值,前提是该值可以解释为真值(请参阅上面的真值测试部分).

http://docs.python.org/library/stdtypes.html#boolean-values一个>

Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

A brief transcript from my interactive console:

Python 2.7.2 (default, Jun 29 2011, 11:10:00) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> 0 == True
False
>>> 1 == True
True
>>> 2 == True
False

Why on earth is this the case?

Edit: For the sake of contrast, consider the is operator.

>>> 0 is False
False
>>> 1 is True
False
>>> 0 is 0
True
>>> True is True
True

That makes a lot of sense because though 1 and True both mean the same thing as the condition of an if statement, they really aren't the same thing.

Edit again: More fun consequences of 1 == True:

>>> d = {}
>>> d[True] = "hello"
>>> d[1]
"hello"

Because Boolean in Python is a subtype of integers. From the documentation:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

http://docs.python.org/library/stdtypes.html#boolean-values