python 逻辑运算符与比较运算符的差别
文章内容摘自:http://www.cnblogs.com/vamei/archive/2012/05/29/2524376.html
逻辑运算符 and, or, not
比较运算符 ==, !=, >, >=, <, <=, in
@陳胡図
查阅下面的讨论:
http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in-python
关键在于:
True和False被当作两个整数对象。在进行比较的时候,没有进行类型转换。比如 -1 == True,相当于 -1 == 1.
如果在条件中,比如not -1中,由于not是boolean运算符,所以进行类型装换(not bool(-1)).
这确实是个有些违反直觉的设定。
查阅下面的讨论:
http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in-python
关键在于:
True和False被当作两个整数对象。在进行比较的时候,没有进行类型转换。比如 -1 == True,相当于 -1 == 1.
如果在条件中,比如not -1中,由于not是boolean运算符,所以进行类型装换(not bool(-1)).
这确实是个有些违反直觉的设定。
建议你把这个给补充上去,官方文档资料归纳总结的真值测试:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
False
>>> 0 == False
True
>>> not 0
True
>>> 1 == True
True
>>> 1 == False
False
>>> not 1
False
>>> -1 == True
False
>>> -1 == False
False
>>> not -1
False
------------
Python 处理 -1 很奇怪么?